我正在关注 Kelly Elias 在 making a WPF checkListBox 上发表的精彩文章.
但是,就我而言,我必须使用反射在代码中创建我的对象。 ListBox 项源正确填充,数据模板正确设置了 ListBox 的样式,从而生成了 CheckBox 列表,但没有显示 CheckBox 的内容。我的数据模板中的绑定(bind)有什么问题?
为简洁起见,请参阅上面的 CheckedListItem 类链接;我的没有变化。
Charge 类,我们将在其中键入 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;
}
XAML 中的数据模板:
<UserControl.Resources>
<DataTemplate x:Key="checkedListBoxTemplate">
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Path=Item.ChargeSectionNumber}" />
</DataTemplate>
</UserControl.Resources>
背后的代码:
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"];
}
结果
基础费用的 ChargeSectionNumber 属性的值为“11418(b)(1)”、“10”、“11”和“13”。
感谢您的协助!
最佳答案
在进行 DataBinding 时,您的类需要实现 INotifyPropertyChanged
以便数据在 UI 中正确显示。一个例子:
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;
}
这显示了类、一个属性 (ChargeSectionNumber) 以及实现 INotifyPropertyChanged
所需的事件和方法。
在您在问题中引用的示例中,您可以看到绑定(bind)到的类也实现了 INotifyPropertyChanged
。
关于c# - 带有 CheckBox 数据模板的 WPF ListBox - Checkbox 的绑定(bind)内容属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30058445/