即时依赖属性

4

我有一个类,它可以实时计算属性,例如:

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中有两个文本框,一个使用双向绑定到半径,另一个使用单向绑定到面积。

我该怎么做才能使对半径文本框的编辑更新面积文本框?


我尝试了 CoerceValue(AreaProperty);InvalidateProperty(AreaProperty);,但它们都没有起作用。 - Palatis
1个回答

3
您可以通过以下几种方式进行操作。
  • For simplicity, you can implement INotifyPropertyChanged, use a regular property for Area, and then trigger the event in the OnDependencyPropertyChanged for RadiusProperty.
  • For more complexity, you'd set AreaProperty using the key privately whenever Radius changes. Your property would look like this.

    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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接