【问题标题】:On-The-Fly DependencyProperties动态依赖属性
【发布时间】:2013-09-12 05:50:32
【问题描述】:

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

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 的文本框进行编辑更新区域的文本框?

【问题讨论】:

  • 我尝试了CoerceValue(AreaProperty);InvalidateProperty(AreaProperty);,但它们都不起作用。

标签: c# wpf dependency-properties


【解决方案1】:

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

  • 为简单起见,您可以实现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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2013-03-11
    • 2020-05-31
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多