Add n rectangles to canvas with MVVM in WPF Add n rectangles to canvas with MVVM in WPF wpf wpf

Add n rectangles to canvas with MVVM in WPF


In a proper MVVM approach you would have a view model with an abstract representation of a list of rectangles, e.g. like this:

public class RectItem{    public double X { get; set; }    public double Y { get; set; }    public double Width { get; set; }    public double Height { get; set; }}public class ViewModel{    public ObservableCollection<RectItem> RectItems { get; set; }}

Then you would have a view that uses an ItemsControl to visualize a collection of such Rect items. The ItemsControl would have a Canvas as its ItemsPanel and an appropriate ItemContainerStyle and ItemTemplate which each bind to the appropriate view model properties. It might look like this:

<ItemsControl ItemsSource="{Binding RectItems}">    <ItemsControl.ItemsPanel>        <ItemsPanelTemplate>            <Canvas/>        </ItemsPanelTemplate>    </ItemsControl.ItemsPanel>    <ItemsControl.ItemContainerStyle>        <Style TargetType="ContentPresenter">            <Setter Property="Canvas.Left" Value="{Binding X}"/>            <Setter Property="Canvas.Top" Value="{Binding Y}"/>        </Style>    </ItemsControl.ItemContainerStyle>    <ItemsControl.ItemTemplate>        <DataTemplate>            <Rectangle Width="{Binding Width}" Height="{Binding Height}" Fill="Black"/>        </DataTemplate>    </ItemsControl.ItemTemplate></ItemsControl>

An alternative without Bindings in Style Setters (which don't work in UWP) might look like this:

<ItemsControl ItemsSource="{Binding RectItems}">    <ItemsControl.ItemsPanel>        <ItemsPanelTemplate>            <Canvas/>        </ItemsPanelTemplate>    </ItemsControl.ItemsPanel>    <ItemsControl.ItemTemplate>        <DataTemplate>            <Rectangle Width="{Binding Width}" Height="{Binding Height}" Fill="Black">                <Rectangle.RenderTransform>                    <TranslateTransform X="{Binding X}" Y="{Binding Y}"/>                </Rectangle.RenderTransform>            </Rectangle>        </DataTemplate>    </ItemsControl.ItemTemplate></ItemsControl>


You can bind the collection of rectangles to an ItemControl and set its height, width and margin:

<ItemsControl  ItemsSource="{Binding Path=RectangleCollection,Mode=TwoWay}">    <ItemsControl.ItemTemplate>        <DataTemplate >            <Canvas>                <Rectangle Stroke="Black" Heigth={some converter} Width={some converter} Margin={Some Converter}>            </Canvas>        </DataTemplate>    </ItemsControl.ItemTemplate></ItemControl>

Just an idea to get you started...