Reputation: 3242
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.
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));
}
}
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 a solution would be much appreciated!
Upvotes: 9
Views: 17962
Reputation: 44038
public ObservableCollection<CheckBoxDatabase> Databases;
is a field.
You should replace it with a Property:
public ObservableCollection<CheckBoxDatabase> Databases {get;set;};
Don't forget INotifyPropertyChanged
!
Upvotes: 8