2015-05-05 59 views
3

我跟随凯利埃利亚斯的优秀文章making a WPF checkListBox带复选框数据模板的WPF列表框 - 复选框不起作用的绑定内容属性

但是,在我的情况下,我必须使用反射在代码中创建我的对象。 ListBox项目源适当填充,并且数据模板正确地设置了ListBox的样式,从而生成CheckBox的列表,但CheckBox没有显示内容。我在做什么我的数据模板绑定错了?

为简洁起见,请参阅上面的CheckedListItem类的链接;矿不变。

的班主任,其中我们将键入CheckedListItem:在XAML

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中:

<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”。

谢谢您的协助!

+0

您现在可以发布图片。 :) – OhBeWise

+0

谢谢OhBeWise,更新! – Bobby

回答

2

在进行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

+0

你是对的!我本应该看到这一点。感谢您及时和全面的答复。 – Bobby

+0

为了更清楚地看到其他人在看这个,上面引用文章中标识的Customer类也没有实现INotifyPropertyChanged。这是作者打算为未来访问者修复的错误。 – Bobby