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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With