[C# WPF] WPF ObservableCollection 클래스를 이용하여 데이터 바인딩 하기

안녕하세요.

 

오늘은 WPF에서 ObservableCollection 클래스를 이용하여 컨트롤에 데이터 바인딩 하는 방법에 대해서 알려 드리려고 합니다.

 

사실, 이 부분은 지난번 ListView에서 ItemSource로 데이터 바인딩 할 때 사용했었는데요.

 

따로 포스팅으로 이부분만 다시 빼서 좀 더 자세히 데이터 바인딩 하는 부분을 보여 드리려고 포스팅 하게 되었습니다.

 

지난번에는 ListView 컨트롤에 데이터 바인딩 하는 방법을 보여 드렸는데요. 이번에는 ListViewListBox 컨트롤에 ObservableCollection 클래스를 이용하여 데이터 바인딩 하는 예제를 보여 드리도록 하겠습니다.

 

 

아래와 같이 WPF 기본 프로젝트를 생성해 주시고, 예제 코드를 따라 쳐 주시기 바랍니다.

 

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<Window x:Class="ObservableCollectionTest.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:ObservableCollectionTest"
        xmlns:Models="clr-namespace:ObservableCollectionTest.Models"
        xmlns:ViewModels="clr-namespace:ObservableCollectionTest.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="500">
    <Window.DataContext>
        <ViewModels:StudentViewModel/>
    </Window.DataContext>
    
    <Window.Resources>
        <Models:StudentModelList x:Key="MyList" />
    </Window.Resources>
 
    <Grid>
        <!--Row 설정-->
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
 
        <Label Grid.Row="0" FontWeight="Bold" FontSize="20" Content="ObservableCollection Example" VerticalContentAlignment="Center" 
               HorizontalContentAlignment="Center"> </Label>
 
        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <!--ListView 데이터 바인딩-->
            <ListView Width="250" Name="uiLv_Main" ItemsSource="{Binding Items}">
                <ListView.View>
                    <GridView AllowsColumnReorder="true">
                        <GridViewColumn DisplayMemberBinding="{Binding Name}" Width="80">
                            <GridViewColumnHeader Content="Name" Width="Auto" />
                        </GridViewColumn>
                        <GridViewColumn DisplayMemberBinding="{Binding Age}" Width="80">
                            <GridViewColumnHeader Content="Age" Width="Auto" />
                        </GridViewColumn>
                        <GridViewColumn DisplayMemberBinding="{Binding Grade}" Width="80">
                            <GridViewColumnHeader Content="Grade" Width="Auto" />
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
 
            <!--ListBox 데이터 바인딩-->
            <ListBox Width="250" x:Name="uiLb_Main" ItemsSource="{Binding Source={StaticResource MyList}}" DisplayMemberPath="Name">
            </ListBox>
        </StackPanel>
    </Grid>
 
    
</Window>
 
cs

 

StudentModel.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
29
30
31
32
33
34
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
 
namespace ObservableCollectionTest.Models
{
    public class StudentModelList : ObservableCollection<StudentModel>
    {
        /// <summary>
        /// 생성자
        /// </summary>
        public StudentModelList()
        {
            Add(new StudentModel() { Name = "범범조조", Age = 28, Grade = "A" });
            Add(new StudentModel() { Name = "안정환", Age = 20, Grade = "B" });
            Add(new StudentModel() { Name = "아이유", Age = 38, Grade = "D" });
            Add(new StudentModel() { Name = "정형돈", Age = 21, Grade = "F" });
            Add(new StudentModel() { Name = "유재석", Age = 74, Grade = "F" });
            Add(new StudentModel() { Name = "박명수", Age = 54, Grade = "D" });
            Add(new StudentModel() { Name = "하하", Age = 47, Grade = "A" });
            Add(new StudentModel() { Name = "광희", Age = 21, Grade = "B+" });
            Add(new StudentModel() { Name = "조세호", Age = 31, Grade = "C-" });
        }
    }
 
    public class StudentModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
    }
}
 
cs

 

StudentViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using ObservableCollectionTest.Models;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace ObservableCollectionTest.ViewModels
{
    public class StudentViewModel
    {
        private readonly StudentModelList items;
 
        public StudentViewModel()
        {
            this.items = new StudentModelList();
        }
 
        public StudentModelList Items
        {
            get { return this.items; }
        }
    }
}
 
cs

 

실행 결과

위와 같이 소스코드를 모두 작성하였다면 이제 아래와 같이 ListView, ListBox 컨트롤에 ObservableCollection 클래스를 이용하여 데이터가 알맞게 바인딩 된 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY