我有一個檢查列表框,並且我希望複選框是多重選擇的,但列表項目上的高亮條是單選。使用下面列出的代碼,複選框是多選的,但是在列表框中沒有高亮條,也不能從列表框中告訴當前選中的項。 (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中設置綁定。 – 2011-12-16 18:26:13