views:

72

answers:

1

Hi, 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?

+1  A: 

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.

Ray Burns