我使用基本形状创建了一个有点复杂的形状。我想在画布上使用这个的倍数,在后面的代码中以编程方式创建。
我考虑过创建一个UserControl,但是封装这个复合形状的最佳方法是什么?
答案 0 :(得分:1)
对于大多数用途,将它们放在ControlTemplate或DataTemplate中效果最好。这是ControlTemplate方式:
<ResourceDictionary>
<ControlTemplate x:Key="MyShape">
<Grid With="..." Height="...">
<Rectangle ... />
<Ellipse ... />
<Path ... />
</Grid>
</ControlTemplate>
</ResourceDictionary>
...
<Canvas ...>
<Control Template="{StaticResource MyShape}" ... />
<Control Template="{StaticResource MyShape}" ... />
<Control Template="{StaticResource MyShape}" ... />
<Control Template="{StaticResource MyShape}" ... />
</Canvas>
以及DataTemplate方式:
<ResourceDictionary>
<DataTemplate x:Key="MyShape">
<Grid With="..." Height="...">
<Rectangle ... />
<Ellipse ... />
<Path ... />
</Grid>
</DataTemplate>
</ResourceDictionary>
...
<Canvas ...>
<ContentPresenter ContentTemplate="{StaticResource MyShape}" ... />
<ContentPresenter ContentTemplate="{StaticResource MyShape}" ... />
<ContentPresenter ContentTemplate="{StaticResource MyShape}" ... />
<ContentPresenter ContentTemplate="{StaticResource MyShape}" ... />
</Canvas>
要在这些选项之间进行选择,请确定您想要的其他功能(如果有)。您可能希望向控件或数据对象添加属性。
您也可以使用ItemsControl及其子类(ListBox,ComboBox等)来适当地显示您的形状,而不是列出单个控件。
替代方法
另一种完全不同的方法是将您的形状集合转换为Drawing对象,并使用DrawingImage或DrawingBrush呈现它。