On-The-Fly DependencyProperties

时间:2013-04-01 13:42:41

标签: c# wpf dependency-properties

我有一个课程,可以即时计算它的属性,例如:

class CircleArea
{
    public double Radius { get; set; }
    public double Area
    {
        get
        {
            return Radius * Radius * Math.PI;
        }
    }
}

通过执行以下操作使其成为DependencyObject:

class CircleArea:
    DependencyObject
{
    public static readonly DependencyProperty RadiusProperty =
        DependencyProperty.Register("Radius", typeof(double), typeof(CircleArea));
    public double Radius
    {
        get { return (double)GetValue(RadiusProperty); }
        set
        {
            SetValue(RadiusProperty, value);
            CoerceValue(AreaProperty);
        }
    }

    internal static readonly DependencyPropertyKey AreaPropertyKey =
        DependencyProperty.RegisterReadOnly("Area", typeof(double), typeof(CircleArea), new PropertyMetadata(double.NaN));
    public static readonly DependencyProperty AreaProperty = AreaPropertyKey.DependencyProperty;
    public double Area
    {
        get
        {
            return Radius * Radius * Math.PI;
        }
    }
}

然后我在XAML中有2个文本框,一个用TwoWay绑定到Radius,另一个用OneWay绑定到Area。

如何对Radius的文本框进行编辑,更新区域的文本框?

1 个答案:

答案 0 :(得分:2)

有几种方法可以做到这一点。

  • 为简单起见,您可以实施INotifyPropertyChanged,为区域使用常规属性,然后在OnDependencyPropertyChanged RadiusProperty中触发事件。
  • 为了更复杂,只要Radius发生变化,您就可以私下使用密钥设置AreaProperty。你的财产看起来像这样。

    public static readonly DependencyProperty RadiusProperty = 
        DependencyProperty.Register(
            "Radius",  
            typeof(double), 
            typeof(CircleArea), 
            new FrameworkPropertyMetadata(0.0, OnRadiusChanged))
    
    
    private static void OnRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
         Area = Radius * Radius * Math.PI;
    }
    
    
    
    private static readonly DependencyPropertyKey AreaKey=
        DependencyProperty.RegisterReadOnly("Area", typeof(double)...
    public static readonly DependencyProperty AreaProperty = AreaKey.DependencyProperty;
    
    public Double Area
    {
        get
        {
            return (Double)GetValue(AreaProperty);
        }
        private set
        {
            SetValue(AreaKey, value);
        }
    }
    

您仍然可以设置单向绑定到Area