【发布时间】:2012-02-25 23:17:12
【问题描述】:
我正在尝试创建一个从标准网格派生的自定义控件。 我添加了一个 ObservableCollection 作为自定义控件的 DependencyProperty。但是,永远无法达到它的获取/设置。在创建与 ObservableCollection 一起正常工作的 DependencyProperty 时,我能否有一些指导方针?
public class MyGrid : Grid
{
public ObservableCollection<string> Items
{
get
{
return (ObservableCollection<string>)GetValue(ItemsProperty);
}
set
{
SetValue(ItemsProperty, value);
}
}
public static DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(ObservableCollection<string>),
typeof(MyGrid), new UIPropertyMetadata(null, OnItemsChanged));
}
【问题讨论】:
-
observablecollection 应该在您的视图模型中,而不是您的控制中...
-
它已经在我的视图模型中了。但是,我如何将它传递给网格?网格不应该也知道如何处理集合吗?
-
您可以将依赖属性定义为 IEnumerable,就像 ItemsControl.ItemsSource 所做的那样。或者发布您的代码,以便有人可以看到它有什么问题。
-
我已经用 IEnumerable 试过了,但也没有用。
-
当您在 XAML 中设置此 Items 属性时,WPF 会将值直接分配给基础依赖项属性,而不是调用您的属性设置器。这也许就是您注意到它没有被调用的原因?
标签: wpf grid dependency-properties