wpf - 如何在 WPF 中实现复选框列表框?

标签 wpf listbox checkbox

尽管在编写 Winforms 应用程序方面有些经验,但就最佳实践和设计模式而言,WPF 的“模糊性”仍然让我难以理解。

尽管在运行时填充了我的列表,但我的列表框显示为空。

我已按照 this helpful article 中的简单说明进行操作无济于事。我怀疑我错过了某种 DataBind()我告诉列表框我已完成修改基础列表的方法。

在我的 MainWindow.xaml 中,我有:

    <ListBox ItemsSource="{Binding TopicList}" Height="177" HorizontalAlignment="Left" Margin="15,173,0,0" Name="listTopics" VerticalAlignment="Top" Width="236" Background="#0B000000">
        <ListBox.ItemTemplate>
            <HierarchicalDataTemplate>
                <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}"/>
            </HierarchicalDataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

在我的代码隐藏中,我有:
    private void InitializeTopicList( MyDataContext context )
    {
        List<Topic> topicList = ( from topic in context.Topics select topic ).ToList();

        foreach ( Topic topic in topicList )
        {
            CheckedListItem item = new CheckedListItem();
            item.Name = topic.DisplayName;
            item.ID = topic.ID;
            TopicList.Add( item );
        }
    }

通过追踪,我知道其中填充了四个项目。

编辑

我改变了TopicListObservableCollection .它仍然不起作用。
    public ObservableCollection<CheckedListItem> TopicList;

编辑#2

我做了两个有帮助的改变:

在 .xaml 文件中:
ListBox ItemsSource="{Binding}"

在我填充列表后的源代码中:
listTopics.DataContext = TopicList;

我得到了一个列表,但是当我刷新它们时,它不会自动更新复选框状态。我怀疑我的进一步阅读将解决这个问题。

最佳答案

假设 TopicList不是 ObservableCollection<T>因此,当您添加没有 INotifyCollection 的项目时changed 被触发以告诉绑定(bind)引擎更新值。

更改您的 TopicListObservableCollection<T>这将解决当前的问题。您还可以填充 List<T>提前,然后绑定(bind)将通过 OneWay 工作;然而 ObservableCollection<T>是一种更稳健的方法。

编辑:

您的 TopicList需要是属性而不是成员变量;绑定(bind)需要属性。它确实 不是 需要是DependencyProperty .

编辑 2:

修改您的ItemTemplate因为它不需要是 HierarchicalDataTemplate

   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>

关于wpf - 如何在 WPF 中实现复选框列表框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4527286/

相关文章:

c# - DataGrid不会立即更新

delphi - tListBox 使用来自其他 ListBox 的自动完成导航

javascript - 选中复选框时有效创建变量,并稍后在代码中使用这些变量

android - 迁移到 AndroidX android :button is not respected for API below Lollipop 后

带有用户控件的 WPF 列表框作为 ItemTemplate DataTemplate 绑定(bind)问题

wpf - DataTemplateSelector和Windows 8

c# - 将列表绑定(bind)到 wpf 中的 listboxitem

ListBox 内的 WPF ComboBox 文本

javascript - 复选框出现问题并选择单击和更改时的交互

wpf - WPF 应用程序的最佳本地数据库解决方案是什么?