“已选中列表框”中没有突出显示的项目

本文关键字:显示 项目 列表 | 更新日期: 2023-09-27 18:18:00

我有一个复选框,我想有复选框是多选择,但列表项上的高亮栏是单一选择。使用下面列出的代码,复选框是多选的,但是列表框中没有高亮条,我也不能从列表框中知道当前选中的是哪个项目。(lbProtocols。SelectedItems总是0)

我错过了什么?

下面是列表框的示例:
<ListBox Name ="lbProtocols" ItemsSource="{Binding AvailableProtocols}">
  <ListBox.ItemTemplate>
    <HierarchicalDataTemplate>
      <CheckBox Content="{Binding ProtocolName}" IsChecked="{Binding IsChecked}" />
    </HierarchicalDataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

下面是将我的observable集合绑定到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"));
        }
    }
}

“已选中列表框”中没有突出显示的项目

您的问题是在ListBoxItem中使用复选框时常见的问题。复选框正在处理单击事件,因此列表框永远不会收到选中该项的通知。如果您在每个项目旁边的文本右侧单击,您将看到该行被选中。

我能建议的最好的解决方案是像这样分割你的DataTemplate

<DataTemplate>
                    <StackPanel Orientation="Horizontal">
                    <CheckBox  IsChecked="{Binding IsChecked}"  />
                    <TextBlock Text="{Binding ProtocolName}" />
                    </StackPanel>
                </DataTemplate>

现在单击文本选择列表框中的项目。如果你想要复选框的点击导致一个项目被选中,你必须绑定到复选框项目的PropertyChanged,然后设置

lbProtocols.SelectedItem = sender