2010-06-04 65 views
3

我創建了一個使用基本形狀的複雜形狀。我想在畫布上使用多個這樣的代碼,在代碼後面以編程方式創建。WPF複合形狀

我曾想過創建一個UserControl,但封裝這個複合形狀的最好方法是什麼?

回答

1

對於大多數情況下,將它們放在ControlTemplate或DataTemplate中效果最好。這裏的控件模板的方式:

<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> 

爲了它們之間選擇,決定你想要什麼額外的功能(如果有的話)。您可能想要將屬性添加到控件或數據對象。

  • 如果使用ControlTemplate,您的自定義控件可以參與屬性繼承併成爲可視樹的一部分,接收所有事件。您還可以在綁定中引用DataContext和TemplatedParent,這更加靈活。
  • 如果使用DataTemplate,可以直接針對模型中的對象工作。

除了列出單獨的控件,您還可以使用ItemsControl及其子類(ListBox,ComboBox等)來適當地呈現您的形狀。

替代方法

另一種完全不同的方式對你的形狀的集合轉換爲圖形對象,並使用DrawingImage或DrawingBrush出示。