Generate array of WPF elements from XAML templates

473 views Asked by At

I have a WPF program in which must draw an array of "bricks" onto a Canvas. There is a handful of different brick types, each of which looks different.

I want each brick type to be drawn using a fairly arbitrary fragment of XAML, e.g.

<Canvas> <!-- or some other per-brick container -->
    <Rectangle Fill="Brown" Stroke="Gray" StrokeThickness="0.1" Canvas.Left="-1" Canvas.Top="-1" Width="2" Height="2" />
    <Ellipse Fill="Blue" Canvas.Left="-0.8" Canvas.Top="-0.8" Width="1.6" Height="1.6"/>
</Canvas>

But I want the code-behind to clone this fragment many times, translating and rotating each copy into position.

This is similar to what an ItemsControl does, except I need to calculate my own brick positions. It also seems similar to what ControlTemplate does, but I don't understand that well enough to solve my problem.

Can anyone explain how it should be done?

1

There are 1 answers

4
Alex Paven On BEST ANSWER

There are several approaches but the one I'd go for is using view models and yes, an ItemsControl. You can specify what type of container the ItemsControl should use and pass a Canvas in, and then you can bind a collection of Bricks to the ItemsSource of the ItemsControl.

Then for each type of brick you can define a DataTemplate that specifies how that type should be rendered. If the items have properties such as X and Y you can bind those to the Canvas.Left and Canvas.Right properties in the DataTemplate and off you go...

A good example of what I mean is https://stackoverflow.com/a/1030191/430661 (the most upvoted answer, not the selected one), except there the item template is specified inline instead of through DataTemplates. Just leave the itemTemplate empty and let the framework select the proper DataTemplate based on type.

Now on the other hand if you expect to have many bricks on screen, or perform complex animations on them, or anything like that... this probably won't perform well enough for that kind of scenarios. But then you're probably better off not using WPF for that anyway...

Let me know if you need more help and I can throw together a sample for you.