WPF ListBox与CheckBox数据模板 - 绑定复选框的Content属性不起作用

3
我正在遵循Kelly Elias的优秀文章制作WPF checkListBox
然而,在我的情况下,我必须使用反射在代码中创建对象。 ListBox项目源适当地填充,数据模板正确地为ListBox设置样式,导致复选框列表,但是CheckBox没有显示任何内容。 我在数据模板中绑定方面做错了什么?
为简洁起见,请参阅上面的链接以获取CheckedListItem类;我的未更改。
我们将键入CheckedListItem的Charge类:
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中的DataTemplate:

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

结果

4 Charges

底层费用的ChargeSectionNumber属性具有值"11418(b)(1)", "10", "11"和"13"。

感谢您的帮助!


现在您可以发布图片了。 :) - OhBeWise
谢谢OhBeWise,已更新! - Bobby
1个回答

2

在进行数据绑定时,您的类需要实现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 所需的事件和方法。

在你提到的那个例子中,你可以看到被绑定的类也实现了 INotifyPropertyChanged 接口。


你说得完全正确!我本应该自己看到那个问题。非常感谢你及时而详尽的回答。 - Bobby
仅供其他查看此内容的人明确,上述引用文章中标识的Customer类也未实现INotifyPropertyChanged。这是作者打算为未来访问者修复的错误。 - Bobby

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接