【发布时间】:2018-02-22 09:47:53
【问题描述】:
目前我正在构建一个具有依赖属性的自定义控件。这个依赖属性应该是一个对象列表。问题是,当我将依赖属性声明为 IEnumerable<> 时,它会起作用并调用回调方法。但是当我选择ICollection<> 或IList<> 时,不会调用依赖属性的回调方法。具有依赖属性的自定义控件在自定义控件库中,被我当前的测试项目引用。
我的自定义控件中的依赖属性实现:
private static readonly FrameworkPropertyMetadata depPropMetaData =
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnStructureChanged));
public static readonly DependencyProperty TreeListStructureProperty =
DependencyProperty.Register(
"TreeListStructure",
typeof(IEnumerable<ITreeListStructure>),
typeof(TreeListView),
depPropMetaData);
public IEnumerable<ITreeListStructure> TreeListStructure
{
get { return (IEnumerable<ITreeListStructure>)this.GetValue(TreeListStructureProperty); }
set { this.SetValue(TreeListStructureProperty, value); }
}
private static void OnStructureChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs eventArgs)
{
; //Breakpoint here
}
在我的带有 MainView 窗口的测试项目中,我只需按如下方式绑定 DataContext:
TestingWrapperViewModel testingVM = new TestingWrapperViewModel();
testingVM.GenerateTestItems(5);
this.DataContext = testingVM;
为了完成 MainView.xaml 中的绑定:
<TreeListView:TreeListView TreeListStructure="{Binding ViewModelList}">
TestingWrapperViewModel 类只包含以下内容:
class TestingWrapperViewModel : INotifyPropertyChanged
{
private List<TestingViewModel> _viewModelList = new List<TestingViewModel>();
public List<TestingViewModel> ViewModelList
{
get { return this._viewModelList; }
set
{
this._viewModelList = value;
OnPropertyChanged("ViewModelList");
}
}
public void GenerateTestItems(uint nAmount)
{
//Just generate some objects for testing
}
//INotifyPropertyChanged Implemenation
}
TestingViewModel 实现了 ITreeListStructure-Interface:
class TestingViewModel : ITreeListStructure, INotifyPropertyChanged
我刚刚列出的代码会触发 OnStructureChanged 事件并返回 DependencyPropertyChangedEventArgs 中指定数量的元素。但是当我将依赖属性声明中的IEnumerable<> 更改为ICollection<> 或IList<> 或List<> 时,根本不会调用回调方法。
我想了解为什么这不起作用。我希望有人能解释一下。
谢谢,
海恩
编辑: 注释格式错误,在此处添加代码:
public void GenerateTestItems(uint nAmount)
{
List<TestingViewModel> temp = new List<TestingViewModel>();
for (uint nCounter = 0; nCounter < nAmount; nCounter++)
{
temp.Add(new TestingViewModel("TestObject" + nCounter.ToString()));
}
ICollection<ITreeListStructure> test1 = temp; //ERROR
IEnumerable<ITreeListStructure> test2 = temp;
this.ViewModelList = temp;
}
EDIT2:更正了我的 EDIT,以便可以看到错误。
【问题讨论】:
标签: c# wpf dependency-properties