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

前端之家收集整理的这篇文章主要介绍了如何在WPF中实现复选框的列表框?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尽管编写 Winforms应用程序有些经验,但是WPF的“模糊”仍然使我在最佳实践和设计模式方面脱颖而出.

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

我已经按照this helpful article的简单说明无效.我怀疑我丢失了一些DataBind()方法,我告诉listBox修改了底层列表.

在我的MainWindow.xaml中,我有:

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

在我的代码隐藏中,我有:

@H_502_8@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.它仍然不起作用

@H_502_8@public ObservableCollection<CheckedListItem> TopicList;

编辑#2

我做了两个更改,帮助:

在.xaml文件中:

@H_502_8@ListBox ItemsSource="{Binding}"

在我填写列表后的源代码中:

@H_502_8@listTopics.DataContext = TopicList;

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

解决方法

使用ObservableCollection<主题>而不是列表<主题>

编辑

它实现INotifyCollectionChanged接口,让WPF知道何时添加/删除/修改项目

编辑2

既然你在代码中设置了TopicList,它应该是一个依赖属性,而不是一个常见的字段

@H_502_8@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));

编辑3

查看项目的更改

>在CheckedListItem中实现INotifyPropertyChanged接口(每个setter都应该调用PropertyChanged(这个,新的PropertyChangedEventArgs(< property name as string>))event)>或从DependencyObject派生CheckedListItem,并将Name,ID,IsChecked转换为依赖属性>或更新它们(topicList [0] = new CheckedListItem(){Name = …,ID = …})

猜你在找的HTML相关文章