[WPF] WPF Converter 사용 방법

안녕하세요.

 

오늘은 WPF에서 Converter 사용 하는 방법에 대해서 알려 드리려고 합니다.

 

Converter 란 해석하자면 변환하다 라는 뜻이 있는데요.

 

WPF에서 Converter 를 사용하는 경우는 여러가지 경우가 있겠지만 보통은, 서로 다른 타입의 변환이 필요한 경우에 Converter를 이용하여 데이터 바인딩을 해줍니다.

 

그러면 실제 예제를 통해서 WPF에서 어떻게 Converter 를 사용하는지 보도록 하겠습니다.

 

제가 예제를 통해 보여드릴건, “나이를 입력하는 TextBox 컨트롤이 있는데 여기서 만약 10, 20, 30대 별 이렇게 나이별로 숫자가 입력했을 때 해당 숫자를 입력 받아서 숫자별로 TextBox 컨트롤의 Foreground 색상을 변경시키는 것을 Converter 를 이용하여 한번 구현해 보도록 하겠습니다.

 

 

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
<Window x:Class="BindingTest.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:BindingTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="160.827" Width="300">
    
    <Window.DataContext>
        <local:Student/>
    </Window.DataContext>
 
    <!--Resource에 Converter 등록-->
    <Window.Resources>
        <local:ButtonTextBrush x:Key="ageConverter"/>
    </Window.Resources>
    
    <Grid>
 
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
 
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
 
        <TextBlock Grid.Row="0" Grid.Column="0" Text="이름 : "
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   Margin="10, 2"/>
        <TextBox Grid.Row="0" Grid.Column="1"
                 Margin="5"
                 Text="{Binding Path=Name, Mode=TwoWay}"/>
 
        <TextBlock Grid.Row="1" Grid.Column="0" Text="나이 : "
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   Margin="10, 2"/>
        <TextBox x:Name="uiTb_Age" Grid.Row="1" Grid.Column="1"
                 Margin="5"
                 Text="{Binding Path = Age}"
                 Foreground="{Binding Path=Age, Mode=TwoWay, Converter={StaticResource ageConverter}}"/>
 
        <TextBlock Grid.Row="2" Grid.Column="0" Text="번호 : "
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   Margin="10, 2"/>
        <TextBox x:Name="uiTb_PhoneNumber" Grid.Row="2" Grid.Column="1"
                 Margin="5"
                 Text="{Binding Path=PhoneNumber}"
                 Foreground="Blue"/>
 
        <Grid Grid.Row="4" Grid.ColumnSpan="2" Height="30">
 
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
 
            <Button Grid.Column="1" Content="확인" Margin="5,3"
                    Foreground="{Binding ElementName=uiTb_Age, Path=Foreground}"/>
            <Button Grid.Column="2" Content="취소" Margin="5,3"/>
 
        </Grid>
 
    </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
using System;
using System.Collections.Generic;
using System.Globalization;
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 BindingTest
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
 
    [ValueConversion(typeof(int), typeof(Brush))]
    class ButtonTextBrush : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof(Brush))
            {
                return null;
            }
 
            int age = Int32.Parse(value.ToString()); // 문자열인 나이를 정수로 변환
 
            return ValueColor(age);
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
 
        public Brush ValueColor(int age)
        {
            if (age >= 10 && age < 20)
            {
                return Brushes.Red;
            }
            else if (age >= 20 && age < 30)
            {
                return Brushes.Green;
            }
            else
            {
                return Brushes.Purple;
            }
        }
    }
}
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
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace BindingTest
{
    public class Student :INotifyPropertyChanged
    {
        /// <summary>
        /// this 생성자
        /// </summary>
        public Student() : this("범범조조""28""000-1111-2222") { }
 
        public Student(string name, string 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 string age;
        public string 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

 

실행 결과

위와 같이 나이가 입력되었을 때, 숫자별로 각각 다른 색상으로 Foreground 컬러가 변경되는 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY