Silverlight Canvas 类(带有 Reflector)有非常简单的实现:3 个附加的依赖属性(Left、Top、ZIndex)和 2 个 MeasureOverride 和 ArrangeOverride 方法的 ovverides,它们没有什么特别的。
但是,如果我使用我的实现,例如:
class MyCanvas : Panel { /* Top and Left dependency properties implementation */ }
然后像标准 Canvas 一样在 XAML 中使用 MyCanvas。这没有按预期工作(我看到空屏幕)。
Canvas 是如何实现的?
-- 附加代码:MyCanvas.cs
public class MyCanvas : Panel
{
public static double GetTop(DependencyObject obj)
{
return (double)obj.GetValue(TopProperty);
}
public static void SetTop(DependencyObject obj, double value)
{
obj.SetValue(TopProperty, value);
}
// Using a DependencyProperty as the backing store for Top. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TopProperty =
DependencyProperty.RegisterAttached("Top", typeof(double), typeof(MyCanvas), new PropertyMetadata(0.0));
public static double GetLeft(DependencyObject obj)
{
return (double)obj.GetValue(LeftProperty);
}
public static void SetLeft(DependencyObject obj, double value)
{
obj.SetValue(LeftProperty, value);
}
// Using a DependencyProperty as the backing store for Left. This enables animation, styling, binding, etc...
public static readonly DependencyProperty LeftProperty =
DependencyProperty.RegisterAttached("Left", typeof(double), typeof(MyCanvas), new PropertyMetadata(0.0));
}
在 XAML 中使用,例如:
<local:MyCanvas>
<Rectangle
local:MyCanvas.Left="10"
local:MyCanvas.Top="10"
Width="100"
Height="100"
Fill="Black" />
</local:MyCanvas>
如果将 MyCanvas 更改为标准 Canvas,我可以在位置 10,10 处查看黑色填充矩形。
<Canvas>
<Rectangle
Canvas.Left="10"
Canvas.Top="10"
Width="100"
Height="100"
Fill="Black" />
</Canvas>