更新子属性时更新依赖项属性

时间:2013-07-10 08:25:37

标签: c# wpf wpf-controls

我有一个继承canvas的类,具有以下依赖属性

public class StorageCanvas : Canvas
{
 public readonly static DependencyProperty StorageProperty = DependencyProperty.Register(
  "Storage",
  typeof(Polygon),
  typeof(StorageCanvas));

 public Polygon Storage
 {
  get { return (Polygon) GetValue(StorageProperty); }
  set { SetValue(StorageProperty, value); }
 }
}

Storage多边形Points被更改/更新时,我可以以某种方式使依赖属性“更新”,而不是要求用新实例替换多边形吗?

2 个答案:

答案 0 :(得分:2)

Polygon.PointsPointCollection,因此您可以订阅Changed事件,然后按照@dowhilefor

的建议致电InvalidateVisual()
public class StorageCanvas : Canvas {
  public static readonly DependencyProperty StorageProperty = DependencyProperty.Register(
    "Storage",
    typeof(Polygon),
    typeof(StorageCanvas),
    new FrameworkPropertyMetadata(null, PropertyChangedCallback));

  public Polygon Storage {
    get {
      return (Polygon)GetValue(StorageProperty);
    }
    set {
      SetValue(StorageProperty, value);
    }
  }

  private static void PropertyChangedCallback(
    DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) {
    var currentStorageCanvas = dependencyObject as StorageCanvas;
    if (currentStorageCanvas == null)
      return;
    var oldPolygon = args.OldValue as Polygon;
    if (oldPolygon != null)
      oldPolygon.Points.Changed -= currentStorageCanvas.PointsOnChanged;
    var newPolygon = args.NewValue as Polygon;
    if (newPolygon == null)
      return;
    newPolygon.Points.Changed += currentStorageCanvas.PointsOnChanged;

    // Just adding the following to test if updates are fine.
    currentStorageCanvas.Children.Clear();
    currentStorageCanvas.Children.Add(newPolygon);
  }

  private void PointsOnChanged(object sender, EventArgs eventArgs) {
    InvalidateVisual();
  }
}

现在,如果Point中的任何个人Storage发生了更改,而未实际重新创建整个对象,则InvalidateVisual()将被解雇。

这个概念就是订阅Changed PointsCollection事件。是否为您做正确的事情是您需要根据自己的要求和逻辑来解决自己的问题。

答案 1 :(得分:0)

相关问题