代码改变世界

WP7备注(29)(Attached Properties|CanvasClone)

2011-05-02 18:31  血糯米Otomii  阅读(225)  评论(0编辑  收藏  举报

首先,Canvas是一个Attached Properties的代表控件,对于Canvas,四个坐标都是Attached Properties,所以进行Canvas的内置机制的Clone,可以让我们更好的了解

首先声明属性

public static readonly DependencyProperty LeftProperty =
DependencyProperty.RegisterAttached("Left",
typeof(double),
typeof(CanvasClone),
new PropertyMetadata(0.0, OnLeftOrTopPropertyChanged));
public static readonly DependencyProperty TopProperty =
DependencyProperty.RegisterAttached("Top",
typeof(double),
typeof(CanvasClone),
new PropertyMetadata(0.0, OnLeftOrTopPropertyChanged));

Get,Set

public static void SetLeft(DependencyObject obj, double value)
{
obj.SetValue(LeftProperty, value);
}
public static double GetLeft(DependencyObject obj)
{
return (double)obj.GetValue(LeftProperty);
}
public static void SetTop(DependencyObject obj, double value)
{
obj.SetValue(TopProperty, value);
}
public static double GetTop(DependencyObject obj)
{
return (double)obj.GetValue(TopProperty);
}

重新安排所有子控件的位置:

static void OnLeftOrTopPropertyChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
CanvasClone parent = VisualTreeHelper.GetParent(obj) as CanvasClone;
if (parent != null)
parent.InvalidateArrange();
}

MeasureOverride:

protected override Size MeasureOverride(Size availableSize)
{
foreach (UIElement child in Children)
child.Measure(new Size(Double.PositiveInfinity,
Double.PositiveInfinity));
return Size.Empty;
}

ArrangeOverride:

protected override Size ArrangeOverride(Size finalSize)
{
foreach (UIElement child in Children)
child.Arrange(new Rect(
new Point(GetLeft(child), GetTop(child)), child.DesiredSize));
return base.ArrangeOverride(finalSize);
}