首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在WPF中实现复选框的ListBox?

如何在WPF中实现复选框的ListBox?
EN

Stack Overflow用户
提问于 2018-05-16 05:13:47
回答 2查看 0关注 0票数 0

虽然在编写Winforms应用程序方面有点经验,但WPF的“模糊性”在最佳实践和设计模式方面仍然没有涉及。

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

在我的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>

在我的code-behind中,我有:

    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 );
        }
    }

其中,通过追踪,我知道正在填充四项。

我已经把TopicList变为ObservableCollection。它仍然不起作用。

    public ObservableCollection<CheckedListItem> TopicList;

在.xaml文件中:

ListBox ItemsSource="{Binding}"

在填充列表之后的源代码中:

listTopics.DataContext = TopicList;

我收到一个列表,但是当我刷新这些列表时,它不会自动更新复选框状态。

EN

回答 2

Stack Overflow用户

发布于 2018-05-16 13:51:30

使用ObservableCollection<Topic>而不是List<Topic>

既然你TopicList在代码中,它应该是依赖项属性,而不是公共字段。

    public ObservableCollection<CheckedListItem> TopicList {
        get { return (ObservableCollection<CheckedListItem>)GetValue(TopicListProperty); }
        set { SetValue(TopicListProperty, value); }
    }
    public static readonly DependencyProperty TopicListProperty =
        DependencyProperty.Register("TopicList", typeof(ObservableCollection<CheckedListItem>), typeof(MainWindow), new UIPropertyMetadata(null));

若要查看项目更改,请执行以下操作

  1. 实施INotifyPropertyChanged接口CheckedListItem(每个设置者都应该调用PropertyChanged(this, new PropertyChangedEventArgs(<property name as string>))活动)
  2. 或导出CheckedListItemDependencyObject,并皈依NameIDIsChecked到依赖属性
  3. 或者完全更新(topicList[0] = new CheckedListItem() { Name = ..., ID = ... })
票数 0
EN

Stack Overflow用户

发布于 2018-05-16 14:34:44

假设TopicList不是ObservableCollection<T>因此,当你添加项目没有INotifyCollection改变被触发告诉绑定引擎更新值。

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

TopicList需要成为一个财产而不是成员变量; 绑定需要属性。它并不需要是一个DependencyProperty

修改你的ItemTemplate因为它不需要是一个HierarchicalDataTemplate

   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100008491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档