开发者

WPF Composite Shape

I have created a somewhat complex shape using basic shapes. I would like to use multiples of this on a canvas, created programmatically in code behind.

开发者_运维技巧

I have thought about creating a UserControl, but what's the best way to encapsulate this composite shape?


For most purposes putting them in a ControlTemplate or DataTemplate works the best. Here's the ControlTemplate way:

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

And the DataTemplate way:

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

To choose between these, decide what additional functionality (if any) you want. You will probably want to add properties to your control or your data object.

  • If you go with a ControlTemplate, your custom control can participate in property inheritance and be part of the visual tree, receiving all the events. You can also refer to both the DataContext and the TemplatedParent in the bindings, which is more flexible.
  • If you go with a DataTemplate, you can work directly against objects in your model.

Instead of listing individual controls you can also use ItemsControl and its subclasses (ListBox, ComboBox, etc) to present your shapes appropriately.

Alternate approach

Another completely different approach is to convert your collection of shapes to a Drawing object and present it using a DrawingImage or a DrawingBrush.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜