【发布时间】:2020-11-23 22:42:44
【问题描述】:
我的对象有一个真正的属性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,而是让调用者通过绑定Converter来监听VideoDimension,这将计算比率。这也是从外部调用者那里知道的太多,而且这绝对是不可扩展的。
【问题讨论】:
标签: wpf data-binding dependency-properties