JBond JBond - 1 year ago 130
C# Question

Implementing a ListBox of CheckBoxes in WPF

Apologies in advance as i'm aware this question has appeared several times. However, i'm struggling to identify where i'm going wrong with my own code. Just looking for a list of checkboxes and names next to them. Currently it compiles ok but the ListBox is empty.

All of the code is within a control called ucDatabases.


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

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; }
isChecked = value;

public string Name
get { return name; }
name = value;

public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string strPropertyName)
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));

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};


Advice and a solution would be much appreciated!

Answer Source

public ObservableCollection<CheckBoxDatabase> Databases; is a field.

You should replace it with a Property:

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

Don't forget INotifyPropertyChanged!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download