DependencyProperty更改时是否重新计算了缓存公共属性?

时间:2018-11-14 01:19:17

标签: c# wpf caching inotifypropertychanged frameworkelement

我想缓存依赖于一个或多个DependencyProperty值的公共属性,以便仅在DependencyProperty更改时才重新计算它们。我的课程继承自FrameworkElementINotifyPropertyChanged。我已经在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); } }
}

我没看到的是:

  1. 如何附加到PropertyChangedEventHandler事件,以便重新计算相关的非DependencyProperty属性?
  2. 如何避免使用DependencyProperty字符串名称?
  3. PropertyChangedCallback中有OverRideMetadata
  4. DependencyProperty个条目,但这是最好的方法吗?

1 个答案:

答案 0 :(得分:0)

我认为您可能正在寻找的CoerceValue仅用于此目的。查找here