wpf – 依赖属性依赖于另一个

前端之家收集整理的这篇文章主要介绍了wpf – 依赖属性依赖于另一个前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何注册一个依赖属性,其值是使用另一个依赖属性的值计算的? @H_502_1@因为WPF在运行时绕过了.NET属性包装器,所以不应该在getter和setter中包含逻辑。解决方案通常是使用PropertyChangedCallbacks。但是这些声明是静态的。

@H_502_1@例如,完成这项设计任务的正确方法是什么?

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(viewmodel));

public double TestDouble
{
  get { return ((double)GetValue(TestDoubleProperty)); }
  set { SetValue(TestDoubleProperty,value); }
}
public static readonly DependencyProperty TestDoubleProperty =
  DependencyProperty.Register("TestDouble",typeof(double),typeof(viewmodel));
@H_502_1@只要依赖不是循环的,是否有适当的方法来完成这个?

嗯…我想你最好看看依赖属性 value coercion.这是一个强制的例子:
public class viewmodel : DependencyObject
{
  public bool TestBool
  {
    get { return (bool)GetValue(TestBoolProperty); }
    set { SetValue(TestBoolProperty,value); }
  }
  public static readonly DependencyProperty TestBoolProperty =
    DependencyProperty.Register("TestBool",typeof(viewmodel),new PropertyMetadata(false,OnTestBoolPropertyChanged));

  private static void OnTestBoolPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
  {
    var vm = (viewmodel)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 = (viewmodel) d;
    var testBool = vm.TestBool;
    return ((testBool) ? (100.0) : (200.0));
  }
}
原文链接:https://www.f2er.com/javaschema/282124.html

猜你在找的设计模式相关文章