c# - Wpf CheckedListbox - 如何获取所选项目

标签 c# wpf xaml

我使用这段代码在 xaml 中制作了一个 CheckedListbox:

                    <ListBox Height="340" ItemsSource="{Binding Sections}" SelectedItem="{Binding SelectedSection}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Path=Item}" />
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

它绑定(bind)到这个集合:

public ObservableCollection<CheckedListItem<String>> Sections { get; set; }
private CheckedListItem<String> _selectedSection;
public CheckedListItem<String> SelectedSection
    {
        get { return _selectedSection; }
        set 
        {
            _selectedSection = value; 
            RaisePropertyChanged("SelectedSection"); 
        }
    }

CheckedListItem 类如下所示:

    public class CheckedListItem<T> : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isChecked;
    private T item;

    public CheckedListItem()
    { }

    public CheckedListItem(T item, bool isChecked = false)
    {
        this.item = item;
        this.isChecked = isChecked;
    }

    public T Item
    {
        get { return item; }
        set
        {
            item = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Item"));
        }
    }


    public bool IsChecked
    {
        get { return isChecked; }
        set
        {
            isChecked = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }
}

我试图在 _selectedSection = value; 中设置一个断点;代码的一部分,但当我选择/取消选择 CheckedListBox 中的项目时它永远不会被触发。

我的问题是每次选择/取消选择时如何获取所选项目?

谢谢

最佳答案

更改您的 XAML

<ListBox Height="340" ItemsSource="{Binding Sections}" SelectedItem="{Binding SelectedSection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ListBoxItem IsSelected="{Binding IsChecked}">
                <CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Path=Item}" />
            </ListBoxItem>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

您可能正在单击实际的 textblock checkbox里面的控件或 square控制不触发 selectionchanged对于 listbox .如果您尝试在矩形边界外单击,请说 whitespace然后它会开火。

如果你只想要 checkbox 会更麻烦作为数据模板,因为您要选择/取消选择 listboxitem ' 基于 checkbox IsChecked 属性。所以只需将它包裹在 ListBoxItem 中你应该可以开始了。

关于c# - Wpf CheckedListbox - 如何获取所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21193242/

相关文章:

c# - 禁用查询的 EF 对象图

c# - 在wpf中制作像Photoshop一样的快速绘图 Canvas

wpf - 在 UserControl 中引用父级的 ResourceDictionary

c# - Entity Framework 中的异步查询和延迟加载

c# - 同一类的析构函数中的对象实例化和垃圾收集

c# - 来自外部程序集的 ApiControllers 的属性路由

c# - 将文件拖放到列表框中

c# - 将文本框绑定(bind)到 View 模型中的对象

c# - 将html字符串内容绑定(bind)到xaml中的Webview

c# - WPF 选项卡顺序工作错误