WPF ListBox with CheckBox data template - Binding Content property of checkbox not working
I am following Kelly Elias' excellent article on creating a WPF checkListBox .
However, in my case, I have to create my objects in code using reflection. The source of the ListBox is populated appropriately and the data template is ordering the ListBox correctly, resulting in a list of CheckBoxes, but Content Content is not displayed for the CheckBox. What am I doing wrong with binding in my data template?
For brevity, see the link above for the CheckedListItem class here; mine has not changed.
The Charge class from which we will type CheckedListItem:
public class Charge
{
public int ChargeId;
public int ParticipantId;
public int Count;
public string ChargeSectionCode;
public string ChargeSectionNumber;
public string ChargeSectionDescription;
public DateTime OffenseDate;
}
DataTemplate in XAML:
<UserControl.Resources>
<DataTemplate x:Key="checkedListBoxTemplate">
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Path=Item.ChargeSectionNumber}" />
</DataTemplate>
</UserControl.Resources>
Code behind:
CaseParticipant participant = _caseParticipants.Where(q => q.ParticipantRole == content.SeedDataWherePath).FirstOrDefault();
ObservableCollection<CheckedListItem<Charge>> Charges = new ObservableCollection<CheckedListItem<Charge>>();
if (participant != null)
{
foreach (Charge charge in participant.Charges)
{
Charges.Add(new CheckedListItem<Charge>(charge));
}
((ListBox)control).DataContext = Charges;
Binding b = new Binding() { Source = Charges };
((ListBox)control).SetBinding(ListBox.ItemsSourceProperty, b);
((ListBox)control).ItemTemplate = (DataTemplate)Resources["checkedListBoxTemplate"];
}
Result
The ChargeSectionNumber property of the base Charges has the values "11418 (b) (1)", "10", "11", and "13".
Thanks for the help!
source to share
When you execute the DataBinding, your class must implement INotifyPropertyChanged
to properly display the data in the UI. Example:
public class Charge : INotifyPropertyChanged
{
private string chargeSectionNumber;
public string ChargeSectionNumber
{
get
{
return chargeSectionNumber;
}
set
{
if (value != chargeSectionNumber)
{
chargeSectionNumber = value;
NotifyPropertyChanged("ChargeSectionNumber");
}
}
}
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
This shows a class, one property (ChargeSectionNumber), and the required event and method to implement INotifyPropertyChanged
.
In the example you referenced in your question, you can see that the class should do as well INotifyPropertyChanged
.
source to share