[WPF] MVVM 패턴 이용하여 Canvas에 Rectangle 동적으로 생성하기

안녕하세요.

 

오늘은 WPF에서 MVVM 패턴을 이용하여 CanvasRectangle 컨트롤을 동적으로 생성해서 그리는 방법에 대해서 알려 드리려고 합니다.

 

소스코드는 매우 간단하므로 별도의 설명 없이 바로 예제 코드를 통해서 어떻게 Canvas에 동적으로 Rectangle을 생성해서 그리는지 보여 드리겠습니다.

 

MainWindow.xaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<Window x:Class="WpfApp4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp4"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
 
    <Grid>
        <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>
    </Grid>
</Window>
cs

 

MainWindowViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System.Collections.ObjectModel;
 
namespace WpfApp4
{
    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 MainViewModel
    {
        public ObservableCollection<RectItem> RectItems { get; set; }
 
        public MainViewModel()
        {
            RectItems = new ObservableCollection<RectItem>();
 
            for (int idx = 1; idx <= 5; idx++)
            {
                RectItems.Add(new RectItem { X = idx * 40, Y = 10, Width = 30, Height = 30 });
            }
        }
    }
}
 
cs

 

실행 결과

위와 같이 5개의 Rectangle을 생성해서 Canvas에 그려지는 것을 확인하실 수 있습니다.

 

좌표나 사이즈, Rectangle의 개수는 얼마든지 변경하여 적용할 수 있기 때문에 기본인 이 코드를 기반으로 여러 부분에 응용하시면 되겠습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY