【发布时间】:2011-10-23 10:38:30
【问题描述】:
我的问题很简单。我有一个绑定到对象 ObservableCollection 的树视图,并且这些对象都有自己的 ObservableCollection。根据用户在我的页面上选择的其他标准,我想动态设置选中哪些复选框。 不幸的是,在我更改了绑定到 IsChecked 的相应 bool 属性后,我的复选框无法更新其 IsChecked 状态。第一次展开任何节点时,复选框将处于正确状态,但之后它们会停止更新。我怀疑这意味着对象在第一次实际显示之前不会被创建/评估。
数据的结构是Silverlight -> ViewModel -> ObservableCollection of StoreGroups LocalStoreGroups -> StoreGroup 有 ObservableCollection of Store Stores
通过调试,我注意到 this.PropertyChanged 没有附加任何处理程序,我想知道这是否是问题所在?
Treeview 控件:
<controls:TreeView ItemsSource="{Binding LocalStoreGroups}" ItemTemplate="{StaticResource TreeviewStoreGroupTemplate}" />
在我的项目中,我使用带有以下 HeirarchalDataTemplates 的树视图:
<UserControl.Resources>
<sdk:HierarchicalDataTemplate x:Key="TreeviewStoreTemplate">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" Content="{Binding DTO.Name}" />
</sdk:HierarchicalDataTemplate>
<sdk:HierarchicalDataTemplate x:Key="TreeviewStoreGroupTemplate" ItemsSource="{Binding Stores}" ItemTemplate="{StaticResource TreeviewStoreTemplate}">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" Content="{Binding DTO.Name}" />
</sdk:HierarchicalDataTemplate>
</UserControl.Resources>
IsSelected 属性的代码(StoreGroup 对象和 Store 对象都有这个属性:
private bool _IsSelected;
public bool IsSelected
{
get { return _IsSelected; }
set
{
_IsSelected = value;
OnPropertyChanged("IsSelected");
}
}
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler temp = this.PropertyChanged;
if (null != temp)
temp(this, e);
}
更改 IsSelected 的代码
foreach (Store s in LocalStoreGroups.SelectMany(sg => sg.Stores))
{
s.IsSelected = false;
}
foreach (StoreLink link in links)
{
Store targetStore = (from s in LocalStoreGroups.SelectMany(sg => sg.Stores) where s.DTO.ID == link.DTO.StoreID select s).FirstOrDefault();
targetStore.IsSelected = true;
}
【问题讨论】:
-
当你设置值时,这是否发生在后台线程中?
-
不,底部的代码(更改 IsSelected 的代码)使用以下方法在 UI 线程上调用:来自 Mvvmlight 的 DispatcherHelper.CheckBeginInvokeOnUI(...)。
-
我想知道您的
OnPropertyChanged方法是如何工作的,因为它不接受字符串,尽管您将字符串传递给它 -
中间有一种我没有复制的方法,它创建了 args,然后将它们传递给我复制的那个。
-
无论如何,这里的赠品应该是没有人订阅 PropertyChanged 事件。事实证明,虽然我实现了 PropertyChanged 事件,但我忘了给类实际提供 INotifyPropertyChanged 接口。
标签: silverlight checkbox treeview