【问题标题】:WPF ListBox with CheckBox data template - Binding Content property of Checkbox not working带有 CheckBox 数据模板的 WPF ListBox - Checkbox 的绑定内容属性不起作用
【发布时间】:2015-05-05 16:29:13
【问题描述】:

我正在关注 Kelly Elias 在making a WPF checkListBox 上的精彩文章。

但是,就我而言,我必须使用反射在代码中创建对象。 ListBox 项目源正在正确填充,并且数据模板正确设置了 ListBox 的样式,从而生成了一个 CheckBox 列表,但没有为 CheckBox 显示任何内容。我的数据模板中的绑定有什么问题?

为简洁起见,请参阅上面的 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”。

感谢您的帮助!

【问题讨论】:

  • 您现在可以发布图片了。 :)
  • 谢谢OhBeWise,更新了!

标签: c# wpf xaml checkbox listbox


【解决方案1】:

在执行 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所需的事件和方法。

在您在问题中引用的示例中,您可以看到绑定到的类也实现了INotifyPropertyChanged

【讨论】:

  • 你完全正确!我自己应该看到的。感谢您及时而彻底的答复。
  • 只是为了让其他人看得清楚,上面引用的文章中确定的 Customer 类也没有实现 INotifyPropertyChanged。这是作者打算为未来的访问者修复的错误。
猜你喜欢
  • 2013-04-12
  • 2013-07-26
  • 2011-05-20
  • 2016-04-26
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
相关资源
最近更新 更多