Just Code‎ > ‎

WPF - Drawing positioned boxes/shapes based on a list in MVVM

posted Dec 21, 2012, 3:24 AM by Peter Henell   [ updated Dec 21, 2012, 3:25 AM ]
I want to draw boxes from a list of shapes specified in my ViewModel.

The view:
<Window x:Class="DrawingBoxesAndLines.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:DrawingBoxesAndLines.ViewModels"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <my:MainWindowViewModel x:Key="mainVM" />
    </Window.Resources>
    
    <Grid DataContext="{StaticResource ResourceKey=mainVM}">
        <ItemsControl Margin="10"
              ItemsSource="{Binding Rectangles}">
            <!--http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx-->
           
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                        <Rectangle Width="{Binding Width}" Height="{Binding Height}" Fill="Red"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
       
            <ItemsControl.ItemContainerStyle>
                <Style>
                    <Setter Property="Canvas.Left" Value="{Binding X}"/>
                    <Setter Property="Canvas.Top" Value="{Binding Y}"/>
                </Style>
            </ItemsControl.ItemContainerStyle>
        </ItemsControl>
    </Grid>
</Window>

ViewModel:
using System.Collections.Generic;

namespace DrawingBoxesAndLines.ViewModels
{
    class Box
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
    }

    class MainWindowViewModel 
    {
        public List<Box> Rectangles { get; set; }

        public MainWindowViewModel()
        {
            Rectangles = new List<Box>();
            Rectangles.Add(new Box { X = 10, Y = 10, Height = 50, Width = 100 });
            Rectangles.Add(new Box { X = 150, Y = 60, Height = 50, Width = 100 });
        }
    }
}
Comments