[WPF] WPF Listbox 데이터바인딩 및 연습

 

안녕하세요.

 

오늘은 WPF에서 Listbox 컨트롤 사용 방법에 대해서 연습 하려고 합니다.

 

그리고 Listbox에 데이터 바인딩을 이용하여 데이터를 넣고 또 여러 이벤트를 이용하여 Listbox 데이터를 다루는 연습을 해보려고 합니다.

 

그럼 별도의 설명 없이 바로 예제 코드를 작성해 보도록 하겠습니다.

 

 

Xaml.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<Window x:Class="ListBoxTest.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:ListBoxTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="400" Width="700">
    <Grid>
        
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="250"/>
        </Grid.ColumnDefinitions>
        
        <ListBox Grid.Column="0" x:Name="uiListMain" HorizontalContentAlignment="Stretch"
                 SelectionChanged="uiListMain_SelectionChanged"
                 SelectionMode="Multiple">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
 
                        <TextBlock Grid.Column="0" 
                                   Text="{Binding Path = strStudentName}"
                                   Margin="2"/>
                        <TextBlock Grid.Column="1" 
                                   Text="{Binding Path = strStudentAge}"
                                   Margin="2"/>
                        <ProgressBar Grid.Column="2"
                                     Minimum="0" 
                                     Maximum="100"
                                     Value="{Binding Path = Point}" 
                                     Margin="5"/>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
 
        <StackPanel Grid.Column="1">
            <Label Content="&lt;학생 관리 List&gt;" Background="Beige" FontWeight="Bold"/>
            <Button x:Name="uibtn_Selected" Content="선택된 학생 보기"
                    Margin="5" Cursor="Hand"
                    Click="uibtn_Selected_Click"/>
            <Button x:Name="uiBtn_PreStudent" Content="이전 학생 보기" Margin="5" Cursor="Hand"
                    Click="uiBtn_PreStudent_Click"/>
            <Button x:Name="uiBtn_NextStudent"  Content="다음 학생 보기"
                    Margin="5" Cursor="Hand"
                    Click="uiBtn_NextStudent_Click"/>
            <Button x:Name="uiBtn_All" 
                    Content="전체 학생 보기" Margin="5" Cursor="Hand"
                    Click="uiBtn_All_Click"/>
        </StackPanel>
 
        <TextBox x:Name="uiTb_Display" Grid.Column="2"/>
    </Grid>
</Window>
 
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
namespace ListBoxTest
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
 
            LoadData();
        }
 
        private void LoadData()
        {
            uiListMain.ItemsSource = GetStudentData();
        }
 
        private List<Student> GetStudentData()
        {
            List<Student> list = new List<Student>();
 
            list.Add(new Student() { strStudentName = "범범조조", strStudentAge = "29" , Point = 90});
            list.Add(new Student() { strStudentName = "아이유", strStudentAge = "29", Point = 30 });
            list.Add(new Student() { strStudentName = "정형돈", strStudentAge = "48", Point = 50 });
            list.Add(new Student() { strStudentName = "유재석", strStudentAge = "50", Point = 75 });
 
            return list;
        }
 
        private void uibtn_Selected_Click(object sender, RoutedEventArgs e)
        {
            if(uiListMain.SelectedItem != null)
            {
                uiTb_Display.Text = $"선택된 학생은 {((Student)uiListMain.SelectedItem).strStudentName } 입니다.";
            }
            else
            {
                MessageBox.Show("학생 선택 먼저 해주세요.");
            }
        }
 
        private void uiListMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(uiListMain.SelectedItem != null)
            {
                this.Title = $"선택된 학생은 {((Student)uiListMain.SelectedItem).strStudentName } 입니다 ";
            }
        }
 
        private void uiBtn_NextStudent_Click(object sender, RoutedEventArgs e)
        {
            if (uiListMain.SelectedItem != null)
            {
                int index = uiListMain.SelectedIndex + 1;
 
                if (index >= uiListMain.Items.Count)
                {
                    index = 0;
                }
 
                uiListMain.SelectedIndex = index;
            }
        }
 
        private void uiBtn_PreStudent_Click(object sender, RoutedEventArgs e)
        {
            if(uiListMain.SelectedItem != null)
            {
                int index = uiListMain.SelectedIndex - 1;
 
                if(index < 0 )
                {
                    index = uiListMain.Items.Count - 1;
                }
 
                uiListMain.SelectedIndex = index;
            }
        }
 
        private void uiBtn_All_Click(object sender, RoutedEventArgs e)
        {
            //uiListMain.SelectAll();
 
            uiTb_Display.Clear();
 
            foreach (Student item in uiListMain.SelectedItems)
            {       
                uiTb_Display.Text += $"선택된 학생은 {item.strStudentName } 입니다. \n";
            }
        }
    }
 
    public class Student
    {
        public string strStudentName { get; set; }
        public string strStudentAge { get; set; }
        public int Point { get; set; }
    }
}
 
cs

 

실행 결과

위와 같이 Student 클래스의 학생 데이터를 리스트박스의 ItemsSource에 넣어 데이터바인딩을 시켜서 학생 정보가 ListBox 컨트롤에 알맞게 들어간 것을 보실 수 있습니다.

 

또한, 버튼의 기능들까지 구현해서 현재 선택된 학생, 이전, 다음, 전체 선택된 학생들의 정보까지 출력해 보았습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY