虽然在编写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;
我收到一个列表,但是当我刷新这些列表时,它不会自动更新复选框状态。
发布于 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));
若要查看项目更改,请执行以下操作
INotifyPropertyChanged
接口CheckedListItem
(每个设置者都应该调用PropertyChanged(this, new PropertyChangedEventArgs(<property name as string>))
活动)CheckedListItem
从DependencyObject
,并皈依Name
,ID
,IsChecked
到依赖属性topicList[0] = new CheckedListItem() { Name = ..., ID = ... }
)发布于 2018-05-16 14:34:44
假设TopicList
不是ObservableCollection<T>
因此,当你添加项目没有INotifyCollection
改变被触发告诉绑定引擎更新值。
将你更改TopicList
为ObservableCollection<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>
https://stackoverflow.com/questions/-100008491
复制相似问题