Bob*_*man 20 wpf checkbox listbox
虽然在编写Winforms应用程序方面有一定的经验,但WPF的"模糊性"在最佳实践和设计模式方面仍然无法实现.
尽管在运行时填充了我的列表,但我的列表框显示为空.
我按照这篇有用的文章的简单说明无济于事.我怀疑我错过了某种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>
Run Code Online (Sandbox Code Playgroud)
在我的代码隐藏中,我有:
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
通过追踪,我知道正在填充四个项目.
编辑
我改成TopicList了ObservableCollection.它仍然无法正常工作.
public ObservableCollection<CheckedListItem> TopicList;
Run Code Online (Sandbox Code Playgroud)
编辑#2
我做了两个更改,有助于:
在.xaml文件中:
ListBox ItemsSource="{Binding}"
Run Code Online (Sandbox Code Playgroud)
在我填充列表后的源代码中:
listTopics.DataContext = TopicList;
Run Code Online (Sandbox Code Playgroud)
我正在获取一个列表,但是当我刷新它们时,它不会自动更新复选框状态.我怀疑我的进一步阅读会解决这个问题.
假设TopicList不是ObservableCollection<T>因此,当您添加项目时,不会INotifyCollection触发任何更改以告知绑定引擎更新该值.
将您更改TopicList为ObservableCollection<T>将解决当前问题.您也可以List<T>提前填充,然后绑定将通过OneWay工作; 然而,这ObservableCollection<T>是一种更强大的方法.
编辑:
您TopicList需要成为属性而不是成员变量; 绑定需要属性.它并不需要是一个DependencyProperty.
编辑2:
修改你的,ItemTemplate因为它不需要是一个HierarchicalDataTemplate
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)
使用ObservableCollection<Topic>代替List<Topic>
编辑
它实现INotifyCollectionChanged接口以在添加/删除/修改项目时通知WPF
编辑2
由于您已TopicList在代码中进行设置,因此它应该是Dependency属性,而不是公共字段
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));
Run Code Online (Sandbox Code Playgroud)
编辑3
查看项目更改
INotifyPropertyChanged接口CheckedListItem(每个设置器应调用PropertyChanged(this, new PropertyChangedEventArgs(<property name as string>))事件)CheckedListItem来自DependencyObject和转换Name,ID,IsChecked给依赖属性topicList[0] = new CheckedListItem() { Name = ..., ID = ... })| 归档时间: |
|
| 查看次数: |
36832 次 |
| 最近记录: |