如何注册一个依赖属性,其值是使用另一个依赖属性的值计算的?
因为WPF在运行时绕过了.NET属性包装器,所以不应该在getter和setter中包含逻辑。解决方案通常是使用PropertyChangedCallbacks。但是这些声明是静态的。
例如,完成这项设计任务的正确方法是什么?
public bool TestBool { get { return (bool)GetValue(TestBoolProperty); } set { SetValue(TestBoolProperty,value); TestDouble = ((value)?(100.0):(200.0)); // HERE IS THE DEPENDENCY } } public static readonly DependencyProperty TestBoolProperty = DependencyProperty.Register("TestBool",typeof(bool),typeof(@R_301_93@l)); public double TestDouble { get { return ((double)GetValue(TestDoubleProperty)); } set { SetValue(TestDoubleProperty,value); } } public static readonly DependencyProperty TestDoubleProperty = DependencyProperty.Register("TestDouble",typeof(double),typeof(@R_301_93@l));
只要依赖不是循环的,是否有适当的方法来完成这个?
嗯…我想你最好看看依赖属性
value coercion.这是一个强制的例子:
public class @R_301_93@l : DependencyObject { public bool TestBool { get { return (bool)GetValue(TestBoolProperty); } set { SetValue(TestBoolProperty,value); } } public static readonly DependencyProperty TestBoolProperty = DependencyProperty.Register("TestBool",typeof(@R_301_93@l),new PropertyMetadata(false,OnTestBoolPropertyChanged)); private static void OnTestBoolPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { var vm = (@R_301_93@l)d; vm.CoerceValue(TestDoubleProperty); } public double TestDouble { get { return ((double)GetValue(TestDoubleProperty)); } set { SetValue(TestDoubleProperty,value); } } public static readonly DependencyProperty TestDoubleProperty = DependencyProperty.Register("TestDouble",new PropertyMetadata(0.0,null,OnCoerceTestDouble)); private static object OnCoerceTestDouble(DependencyObject d,object baseValue) { var vm = (@R_301_93@l) d; var testBool = vm.TestBool; return ((testBool) ? (100.0) : (200.0)); } }