On-The-Fly DependencyProperties

本文关键字:DependencyProperties On-The-Fly | 更新日期: 2023-09-27 18:06:44

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

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中有两个文本框,一个是单向绑定到Radius,另一个是单向绑定到Area。

我应该做些什么来编辑半径的文本框更新区域的文本框?

On-The-Fly DependencyProperties

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

  • 为简单起见,您可以实现INotifyPropertyChanged,为Area使用常规属性,然后为RadiusProperty触发OnDependencyPropertyChanged中的事件。
  • 为了更复杂,您将在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

相关文章:
  • 没有找到相关文章