wpf - 从其他 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
一种懒惰的方式计算。
到目前为止,我发现的工作解决方法是:
- 制作
VideoRatioProperty
自己的DependencyProperty
,并在VideoDimension
更改时手动更新。这并不理想,因为:VideoRatioProperty
如果没有人在听,可能会一无所获。- 它创造了第二个事实来源。它使一个能够修改
VideoRatio
而不是VideoDimension
. 这可以通过RegisterReadOnly
保护它免受public
调用者的影响来缓解,但所有者对象仍然可以修改它。
- 仅用
VideoRatio
作轻量级的 getter,可以即时计算值。但是随后很难让其他元素绑定到它,因为它们应该听VideoDimensionProperty
通知器,但从VideoRatio
. 从外部调用者那里知道的太多了。 - 根本不使用,而是让调用者使用可以计算比率的绑定来
VideoRatio
收听。从外部调用者那里知道的也太多了,而且这绝对是不可扩展的。VideoDimension
Converter
解决方案
“白白计算,如果没有人听的话”
源对象不应该关心是否有人“听”它。无论如何,它都应该更新其状态,因此这不是问题。
“但接下来就很难让其他元素与之绑定了……”
您可以在您的课程中实现并在您想要通知订阅者时INotifyPropertyChanged
引发PropertyChanged
事件。VideoDimension
“但所有者对象仍然可以修改它”
它不仅可以——它应该。这是它的责任。是使用键显式设置只读依赖项属性还是PropertyChanged
为只读 CLR 属性引发事件只是个人喜好问题。
您不应该强制外部调用者使用转换器来获取值。其他两个选项非常好,应该被视为解决方案而不是解决方法。
推荐阅读
- r - as.data.frame.default 中的错误:无法将类强制转换为 data.frame - 将按钮提交到 .csv
- node.js - Hyperledger Fabric 2.3 连接问题
- node.js - Node JS 加密模块困扰 Express 会话
- api - Amadeus Safe Place API
- php - laravel api 的端点命名
- google-sheets - 基于其他工作表的列获取第 4 列
- javascript - 如果文本溢出,如何切换显示更多按钮
- javascript - 无法以角度访问数据成员
- docker - Docker for Windows 无法访问 RabbitMQ ip,除非端口绑定到 localhost
- javascript - Deno 中 writeJson 的格式输出