【发布时间】:2011-02-20 19:27:24
【问题描述】:
我有一个名为 MyComponent 的类,它有一个名为 BackgroundProperty 的 DependencyProperty。
public class MyComponent
{
public MyBackground Background
{
get { return (MyBackground)GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
public static readonly DependencyProperty BackgroundProperty =
DependencyProperty.Register("Background", typeof(MyBackground),
typeof(MyComponent), new FrameworkPropertyMetadata(default(MyBackground), new PropertyChangedCallback(OnPropertyChanged)));
}
MyBackground 是一个派生自 DependencyObject 的类,它有一些 DependencyProperties。
public class MyBackground : DependencyObject
{
public Color BaseColor
{
set { SetValue(BaseColorProperty, value); }
get { return (Color)GetValue(BaseColorProperty); }
}
public static readonly DependencyProperty BaseColorProperty =
DependencyProperty.Register("BaseColor", typeof(Color),
typeof(MyBackground ), new UIPropertyMetadata(Colors.White));
[...]
}
现在,我想要的是当 MyBackground 中的属性发生更改时,通知 MyComponent MyBackground 已更改,并调用名为 OnPropertyChanged 的 PropertyChangedCallback。
【问题讨论】:
-
我有点困惑你为什么需要它。通常情况正好相反,DP 用于绑定,当它们发生变化时,您想通知 DP。为什么你需要反过来呢?
-
你是什么意思这是倒退@Omribitan?这是标准的 WPF。如果我修改依赖属性的值,绑定到该属性的所有东西都会立即知道它。这就是依赖属性的用途——WPF 的数据绑定就是建立在这个概念之上的。
-
@BrainSlugs83 想象一个控件的 Visibility 绑定到 ViewModel 的类上的一个属性,我们称之为
IsVisibile。Visibility是 DP,IsVisibile是一个简单的属性。通常发生的情况是,当IsVisible发生更改时,您希望通知 UI(主要是使用INotifyPropertyChanged)让DP知道它的值已更改,而不是相反...
标签: wpf dependency-properties notify dependencyobject