首页 > 解决方案 > 从其他 DependencyProperty 派生的只读 DependencyProperty

问题描述

我的对象有一个真正的属性VideoDimension和一个VideoRatio基本上是前者的“简化”版本的属性。我正在寻找一种以最优雅的方式将两者连接起来的方法。

public static readonly DependencyProperty VideoDimensionProperty = 
    DependencyProperty.Register(
        nameof(VideoDimension), 
        typeof(Point), 
        typeof(MyControl), 
        new PropertyMetadata(new Point(0, 0))
    );
public Point VideoDimension
{
    get { return (Point)GetValue(VideoDimensionProperty); }
    set { SetValue(VideoDimensionProperty, value); }
}


public static readonly DependencyProperty VideoRatioProperty = 
    MysteryFunction(VideoDimensionProperty, (value) =>
        {
            Point point = (Point)value;
            return point.X / point.Y;
        });
public double VideoRatio
{
    get { return (double)GetValue(VideoRatioProperty); }
}

上面这可能MysteryFunction是什么?我想以VideoRatio一种懒惰的方式计算。

到目前为止,我发现的工作解决方法是:

标签: wpfdata-bindingdependency-properties

解决方案


“白白计算,如果没有人听的话”

源对象不应该关心是否有人“听”它。无论如何,它都应该更新其状态,因此这不是问题。

“但接下来就很难让其他元素与之绑定了……”

您可以在您的课程中实现并在您想要通知订阅者时INotifyPropertyChanged引发PropertyChanged事件。VideoDimension

“但所有者对象仍然可以修改它”

它不仅可以——它应该。这是它的责任。是使用键显式设置只读依赖项属性还是PropertyChanged为只读 CLR 属性引发事件只是个人喜好问题。

您不应该强制外部调用者使用转换器来获取值。其他两个选项非常好,应该被视为解决方案而不是解决方法。


推荐阅读