1

我有一个类继承画布具有以下依赖属性

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,而不是要求用新实例替换多边形?

4

2 回答 2

2

那么Polygon.Points是一个PointCollection,所以你可以订阅Changed它的事件,然后InvalidateVisual()按照@dowhilefor 的建议调用

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();
  }
}

因此,现在如果任何个人发生PointStorage变化,但没有实际重新创建整个对象,InvalidateVisual()将被解雇。

这个概念只是关于Changed订阅PointsCollection. 这是否适合您是您需要根据自己的要求和逻辑自己解决的问题。

于 2013-07-10T09:44:54.817 回答
0

使用影响渲染元数据选项注册依赖属性。

http://msdn.microsoft.com/en-us/library/system.windows.frameworkpropertymetadata.affectsrender.aspx

于 2013-07-10T09:12:45.947 回答