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 中有 2 个文本框,一个将 TwoWay 绑定到 Radius,另一个将 OneWay 绑定到 Area。

我应该怎么做才能对 Radius 的文本框进行编辑更新区域的文本框?

4

1 回答 1

3

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

  • 为简单起见,您可以实现INotifyPropertyChanged,使用 Area 的常规属性,然后在OnDependencyPropertyChangedfor中触发事件RadiusProperty
  • 为了更复杂,您可以AreaProperty在 Radius 更改时私下使用密钥进行设置。你的财产看起来像这样。

    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.

于 2013-04-01T14:38:55.927 回答