我想缓存依赖于一个或多个DependencyProperty
值的公共属性,以便仅在DependencyProperty
更改时才重新计算它们。我的课程继承自FrameworkElement
和INotifyPropertyChanged
。我已经在Implementing INotifyPropertyChanged的后面部分回答了。简化的班级:
public class ElementBase : FrameworkElement, INotifyPropertyChanged {
static ElementBase() {
WidthProperty.OverrideMetadata(typeof(ElementBase), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnCalculatedValueChanged)));
HeightProperty.OverrideMetadata(typeof(ElementBase), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnCalculatedValueChanged)));
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private static void OnCalculatedValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
// how can property's string name be avoided
switch (e.Property.ToString()) { // force update of non-dependency properties
case "Height": // is there a better way to force the recalculations?
((ElementBase)d).HalfHeight = 0.0; // set overwrites with calculated value
((ElementBase)d).Center = new Point(0, 0); // set overwrites with calculated value
break;
case "Width":
((ElementBase)d).HalfWidth = 0.0; // set overwrites with calculated value
((ElementBase)d).Center = new Point(0, 0); // set overwrites with calculated value
break;
default: break;
}
}
// Caching of the public properties.
private double halfWidth; // cached calculated half width
public double HalfWidth { get => halfWidth; set { halfWidth = Width / 2.0; } }
private double halfHeight; // cached calculated half height
public double HalfHeight { get => halfHeight; set { halfHeight = Height / 2.0; } }
private Point center; // cached calculated center point
public Point Center { get => center; set { center = new Point(HalfWidth, HalfHeight); } }
}
我没看到的是:
PropertyChangedEventHandler
事件,以便重新计算相关的非DependencyProperty
属性?DependencyProperty
字符串名称? PropertyChangedCallback
中有OverRideMetadata
的DependencyProperty
个条目,但这是最好的方法吗?