【发布时间】:2011-12-16 17:01:18
【问题描述】:
我有一个选中的列表框,我希望复选框是多选的,但列表项上的突出显示栏是单选的。使用下面列出的代码,复选框是多选的,但列表框中没有突出显示栏,我也无法从列表框中判断当前选中了哪个项目。 (lbProtocols.SelectedItems 始终为 0)
我错过了什么?
这是列表框的 xaml:
<ListBox Name ="lbProtocols" ItemsSource="{Binding AvailableProtocols}">
<ListBox.ItemTemplate>
<HierarchicalDataTemplate>
<CheckBox Content="{Binding ProtocolName}" IsChecked="{Binding IsChecked}" />
</HierarchicalDataTemplate>
</ListBox.ItemTemplate>
</ListBox>
下面是将我的可观察集合绑定到列表框的代码:
public ObservableCollection<CheckedListItem> AvailableProtocols;
AvailableProtocols = new ObservableCollection<CheckedListItem>();
CheckedListItem item1 = new CheckedListItem(0, "first", false);
item1.IUPropertyChanged += new PropertyChangedEventHandler(item_IUPropertyChanged);
CheckedListItem item2 = new CheckedListItem(1, "second", true);
item2.IUPropertyChanged += new PropertyChangedEventHandler(item_IUPropertyChanged);
CheckedListItem item3 = new CheckedListItem(3, "third", false);
item3.IUPropertyChanged += new PropertyChangedEventHandler(item_IUPropertyChanged);
AvailableProtocols.Add(item1);
AvailableProtocols.Add(item2);
AvailableProtocols.Add(item3);
lbProtocols.ItemsSource = AvailableProtocols;
这里是 CheckedListItem 类:
public class CheckedListItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangedEventHandler IUPropertyChanged;
public CheckedListItem(){ }
public CheckedListItem(int id, string name, bool check)
{
ID = id;
ProtocolName = name;
IsChecked = check;
}
public int ID { get; set; }
public string ProtocolName { get; set; }
private bool _IsChecked;
public void SetCheckedNoNotify(bool check)
{
_IsChecked = check;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
}
public bool IsChecked
{
get { return _IsChecked; }
set
{
_IsChecked = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
if (IUPropertyChanged != null)
IUPropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
}
}
}
【问题讨论】:
-
您使用 HeirarchicalDataTemplate 而不是 DataTemplate 是否有原因?此外,如果您从代码隐藏中设置 ItemsSource,则无需在 XAML 中设置绑定。