尽管在编写 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 );
}
}
通过追踪,我知道其中填充了四个项目。
编辑
我改变了
TopicList
到 ObservableCollection
.它仍然不起作用。 public ObservableCollection<CheckedListItem> TopicList;
编辑#2
我做了两个有帮助的改变:
在 .xaml 文件中:
ListBox ItemsSource="{Binding}"
在我填充列表后的源代码中:
listTopics.DataContext = TopicList;
我得到了一个列表,但是当我刷新它们时,它不会自动更新复选框状态。我怀疑我的进一步阅读将解决这个问题。
最佳答案
假设 TopicList
不是 ObservableCollection<T>
因此,当您添加没有 INotifyCollection
的项目时changed 被触发以告诉绑定(bind)引擎更新值。
更改您的 TopicList
到 ObservableCollection<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/