c# - 带有 CheckBox 数据模板的 WPF ListBox - Checkbox 的绑定(bind)内容属性不起作用

标签 c# wpf xaml checkbox listbox

我正在关注 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"];
}

结果

4 Charges

基础费用的 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/

相关文章:

c# - 将数组拆分为 2 个数组 C#

c# - Ef-Core - 我可以使用什么正则表达式在 Db 拦截器中用 nolock 替换表名

c# - 使用 Sqlite.dll 错误

c# - 使用 RunAs 提示启动 WPF 应用程序

WPF 形状矩形绑定(bind)

c# - 检测是否在 C# 中按下了任何键(不是 A、B,而是任何键)

.net - Silverlight 本地化 - 如何覆盖 Windows 区域性

wpf - 如何在透明矩形上绘制阴影?

c# - UWP:- 拖动项目时如何创建拖动 UI(指示要放置项目的位置)?

wpf - 获取 ViewModel 中的 TextBox 值