[WPF] WPF Listbox 컨트롤 Group 별로 필터하기

안녕하세요.

 

오늘은 WPF에서 Listbox 컨트롤 사용방법에 대해서 알려 드리려고 합니다.

 

그 중에서도, ListBox 컨트롤에서 제공해주는 기능인 Group에 대해서 알아 보려고 하는데요.

 

그룹은 말 그대로 특정 대상에 따라 묶어서 그룹을 짓는 걸 얘기하는데요.

 

WPF에서 코드로 어떻게 Group을 만드는지 보여 드리도록 하겠습니다.

 

그럼 예제 프로그램을 구현해 보도록 하겠습니다.

 

 

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
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
<Window x:Class="BindingTest.Window3"
        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:BindingTest"
        mc:Ignorable="d"
        Title="Window3" Height="450" Width="400">
 
    <Window.Resources>
        <DataTemplate x:Key="StudentTemplate">
 
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
 
                <Image Grid.Row="0" Grid.Column="0" Grid.RowSpan="2"
                               Source="https://cdn0.iconfinder.com/data/icons/kameleon-free-pack/110/Man-14-128.png"
                               Width="64" Height="64"/>
                <TextBlock Grid.Row="0" Grid.Column="1" HorizontalAlignment="Center"
                                   VerticalAlignment="Center">성명 :</TextBlock>
                <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Path=Name}"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Center"/>
 
                <Button x:Name="btnDelete" Grid.Row="1" Grid.Column="3" Content="삭제"
                                Click="btnDelete_Click"
                                Tag="{Binding Name}"
                                Margin="3"/>
 
                <TextBlock Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center"
                                   VerticalAlignment="Center">나이 :</TextBlock>
                <TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding Path=Age}"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Center"/>
 
                <TextBlock Grid.Row="2" Grid.Column="1"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Center">핸드폰번호 :</TextBlock>
                <TextBlock Grid.Row="2" Grid.Column="2" Text="{Binding Path=PhoneNumber}"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Center"/>
 
                <Border Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" VerticalAlignment="Bottom" BorderBrush="Black"
                                BorderThickness="0,0,0,1" HorizontalAlignment="Stretch"/>
 
            </Grid>
 
        </DataTemplate>
    </Window.Resources>
 
    <Window.DataContext>
        <local:StudentList x:Name="studentList"/>
    </Window.DataContext>
 
    <Grid>
 
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
 
        <ListBox Grid.Column="0" IsSynchronizedWithCurrentItem="True"
                 Name="uiLb_Student" ItemsSource="{Binding}"
                 ItemTemplate="{StaticResource StudentTemplate}"
                 HorizontalContentAlignment="Stretch">
 
            <!--ListBox 컨트롤 그룹 스타일 지정-->
            <ListBox.GroupStyle>
                <GroupStyle>
                    <GroupStyle.HeaderTemplate>
                        <DataTemplate>
                            <TextBlock Background="Beige" Foreground="Black" FontWeight="Bold">
                                <TextBlock Text="{Binding Name}"/>
                                (<TextBlock Text="{Binding ItemCount}"/>명)
                            </TextBlock>
                        </DataTemplate>
                    </GroupStyle.HeaderTemplate>
                </GroupStyle>
            </ListBox.GroupStyle>
 
        </ListBox>
 
        <StackPanel Grid.Column="1">
            <Button x:Name="uiBtn_Group"
                    Content="그룹별 지정"
                    Click="uiBtn_Group_Click"/>
        </StackPanel>
 
    </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
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
 
namespace BindingTest
{
    /// <summary>
    /// Window3.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class Window3 : Window
    {
        public Window3()
        {
            InitializeComponent();
        }
 
        /// <summary>
        /// 리스트 항목 삭제 버튼 이벤트 핸들러
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
 
            if (btn.DataContext is Student)
            {
                Student deleteme = (Student)btn.DataContext;
                studentList.Remove(deleteme);
            }
        }
 
        /// <summary>
        /// 리스트항목 그룹 버튼 이벤트 핸들러
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_Group_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView list = CollectionViewSource.GetDefaultView(studentList);
 
            if (list.GroupDescriptions.Count == 0)
            {
                list.GroupDescriptions.Add(
                    new PropertyGroupDescription("Age"new AgeToRangeConverter())
                    );
 
                //list.GroupDescriptions.Add(
                //        new PropertyGroupDescription("Name")
                //    );
            }
            else
            {
                list.GroupDescriptions.Clear();
            }
        }
    }
 
    /// <summary>
    /// 그룹핑 IConverter 클래스
    /// </summary>
    [ValueConversion(typeof(int), typeof(string))]
    class AgeToRangeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return ((int)value) >= 20 ? "성년" : "미성년";
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
 
cs

 

Student.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
using System.ComponentModel;
 
namespace BindingTest
{
    public class Student :INotifyPropertyChanged
    {
        /// <summary>
        /// this 생성자
        /// </summary>
        public Student() : this("범범조조"28"000-1111-2222") { }
 
        public Student(string name, int age, string number)
        {
            this.Name = name;
            this.Age = age;
            this.PhoneNumber = number;
        }
 
        private string name;
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
 
        private int age;
        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
                OnPropertyChanged("Age");
            }
        }
 
        private string phoneNumber;
 
        public string PhoneNumber
        {
            get
            {
                return phoneNumber;
            }
            set
            {
                phoneNumber = value;
                OnPropertyChanged("PhoneNumber");
            }
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
 
        void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));
        }
    }
}
 
cs

 

StudentList.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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace BindingTest
{
    public class StudentList : ObservableCollection<Student>
    {
        public StudentList()
        {
            Add(new Student() { Name = "범범조조", Age = 18, PhoneNumber = "010-2345-2222" });
            Add(new Student() { Name = "안정환", Age = 10, PhoneNumber = "010-4345-2222" });
            Add(new Student() { Name = "아이유", Age = 18, PhoneNumber = "010-5345-2672" });
            Add(new Student() { Name = "정형돈", Age = 21, PhoneNumber = "010-3345-2752" });
            Add(new Student() { Name = "유재석", Age = 74, PhoneNumber = "010-4345-2752" });
            Add(new Student() { Name = "박명수", Age = 14, PhoneNumber = "010-5345-2752" });
            Add(new Student() { Name = "하하", Age = 17, PhoneNumber = "010-8345-2752" });
            Add(new Student() { Name = "광희", Age = 21, PhoneNumber = "010-6745-2752" });
            Add(new Student() { Name = "조세호", Age = 31, PhoneNumber = "010-6345-2752" });
        }
    }
}
 
cs

 

실행 결과

 

 

위와 같이 여러 학생들 중에서 성년과, 미성년으로 Group으로 나뉘어서 보여지는 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY