I have made a CheckedListBox using the following:
<ListBox x:Name="lst_checkBoxList" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and am populating it using the following:
public List<CheckedListItem> listItems = new List<CheckedListItem>();
public class CheckedListItem
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsChecked { get; set; }
public CheckedListItem(int id, string name, bool ischecked)
{
Id = id;
Name = name;
IsChecked = ischecked;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
listItems.Add(new CheckedListItem(0, "item 1", false));
listItems.Add(new CheckedListItem(0, "item 2", false));
listItems.Add(new CheckedListItem(0, "item 3", false));
listItems.Add(new CheckedListItem(0, "item 4", false));
lst_checkBoxList.ItemsSource = listItems;
listItems[0].IsChecked = true; //This correctly sets the first CheckBox as checked.
}
private void button2_Click(object sender, RoutedEventArgs e)
{
listItems[0].IsChecked = true; //This does not affect the CheckBox, despite changing the value it is bound to.
}
If I change the data behind one of the CheckBoxes immediately after setting the ItemsSource, the CheckBox is ticked accordingly, but if I try to change the value anywhere else in the code the CheckBox remains unchecked…can anyone help me work out why?
You need to notify the control that the property it is bound to has been updated, by implementing the
INotifyPropertyChangedinterface inCheckedListItem: