Embedding ListBox from CheckBoxes in WPF

I apologize in advance, because I know that this question has appeared several times. However, I am struggling to determine where I am wrong in my own code. Just find the list of checkboxes and names next to them. Currently it compiles fine, but the ListBox is empty.

All code is inside a control called ucDatabases.

XAML:

<ListBox Grid.Row="4" ItemsSource="{Binding Databases}"> <ListBox.ItemTemplate> <DataTemplate> <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" Margin="5 5 0 0"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

C # code:

  public ObservableCollection<CheckBoxDatabase> Databases; public class CheckBoxDatabase : INotifyPropertyChanged { private string name; private bool isChecked; public Database Database; public bool IsChecked { get { return isChecked; } set { isChecked = value; NotifyPropertyChanged("IsChecked"); } } public string Name { get { return name; } set { name = value; NotifyPropertyChanged("Name"); } } public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string strPropertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName)); } } 

A helper method to populate some test data:

 private void SetTestData() { const string dbAlias = "Database "; Databases = new ObservableCollection<CheckBoxDatabase>(); for (int i = 0; i <= 4; i++) { var db = new Database(string.Format(dbAlias + "{0}", i)); var newCBDB = new CheckBoxDatabase {Database = db, IsChecked = false, Name = db.Name}; Databases.Add(newCBDB); } } 

Advice and decision will be very grateful!

+7
source share
1 answer

public ObservableCollection<CheckBoxDatabase> Databases; - this field.

You must replace it with Property:

public ObservableCollection<CheckBoxDatabase> Databases {get;set;};

Do not forget INotifyPropertyChanged !

+6
source

All Articles