在XAML中或通过绑定设置依赖属性时,运行时将始终绕过实例属性别名并直接调用
GetValue
和
SetValue
. 正是因为这样,才不会调用实例设置器。
您可能希望考虑在依赖属性中注册一个方法,当该属性更改时将调用该方法。在创建
PropertyMetadata
对于依赖属性。
我相信下面的例子可以实现你想要做的。在这个例子中,我的类有两个依赖属性,分别命名为First和Second。当我设置第一个值时,将调用我的更改处理程序,并设置第二个值。
public class DependencyPropertyTest : DependencyObject
{
public static readonly DependencyProperty FirstProperty;
public static readonly DependencyProperty SecondProperty;
static DependencyPropertyTest()
{
FirstProperty = DependencyProperty.Register("FirstProperty",
typeof(bool),
typeof(DependencyPropertyTest),
new PropertyMetadata(false, FirstPropertyChanged));
SecondProperty = DependencyProperty.Register("SecondProperty",
typeof(string),
typeof(DependencyPropertyTest),
new PropertyMetadata(null));
} // End constructor
private bool First
{
get { return (bool)this.GetValue(FirstProperty); }
set { this.SetValue(FirstProperty, value); }
} // End property First
private string Second
{
get { return (string)this.GetValue(SecondProperty); }
set { this.SetValue(SecondProperty, value); }
} // End property Second
private static void FirstPropertyChanged(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs ea)
{
DependencyPropertyTest instance = dependencyObject as DependencyPropertyTest;
if (instance == null)
{
return;
}
instance.Second = String.Format("First is {0}.", ((bool)ea.NewValue).ToString());
} // End method FirstPropertyChanged
} // End class DependencyPropertyTest
希望有帮助。