依赖属性依赖于另一个 [英] Dependency Property dependent on another

查看:100
本文介绍了依赖属性依赖于另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何注册一个依赖关系属性,该依赖关系属性的值是使用另一个依赖关系属性的值计算的?

How can one register a dependency property whose value is calculated using the value of another dependency property?

由于WPF在运行时绕过.NET属性包装器,一次,不应在getter和setter中包含逻辑。解决方案通常是使用 PropertyChangedCallback s。但是,这些被声明为静态的。

Because the .NET property wrappers are bypassed by WPF at run-time, one should not include logic in the getters and setters. The solution to that is typically to use PropertyChangedCallbacks. But those are declared static.

例如,完成此人为任务的正确方法是什么:

For example, what is the proper way to accomplish this contrived task:

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

只要依赖项不是循环的,是否有适当的方法来实现?

As long as the dependency is not circular, is there a proper means to accomplish this?

推荐答案

嗯...我想您最好看看依赖属性值强制。这是一个带有强制性的示例:

Hmmm... I think you'd better look at dependency properties value coercion. Here is an example with 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(bool), 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", typeof(double), typeof(ViewModel), 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));
  }
}

这篇关于依赖属性依赖于另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆