WPF/개발

WPF RadioButton Enum Binding 방법

푸코잇 2024. 5. 16. 17:03
728x90

WPF의 RadioButton 컨트롤에 Enum을 바인딩하는 방법에 대해 알아보자.

 

1. Animal 열거형 정의

namespace RadioButtonEnumBinding
{
    public enum Animal
    {
        Dog,
        Cat,
        Pig
    }
}

 

2. 바인딩을 위한 프로퍼티 정의

namespace RadioButtonEnumBinding
{
    public class MainWindowVM : Notifier
    {
        private Animal _selectedAnimal;
        public Animal SelectedAnimal
        {
            get { return _selectedAnimal; }
            set
            {
                _selectedAnimal = value;
                OnPropertyChanged(nameof(SelectedAnimal));
            }
        }
    }
    
    public class Notifier : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

 

3. enum 값 비교를 위한 Converter 정의

namespace RadioButtonEnumBinding
{
    /// <summary>
    /// value와 parameter 값 비교 컨버터 클래스
    /// </summary>
    public class ComparisonConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value?.Equals(parameter);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value?.Equals(true) == true ? parameter : Binding.DoNothing;
        }
    }
}

 

4. RadioButton에 Enum 바인딩

<Window x:Class="RadioButtonEnumBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:RadioButtonEnumBinding"
        mc:Ignorable="d"
        Title="라디오버튼 enum 바인딩" Height="120" Width="400">
    <Window.DataContext>
        <local:MainWindowVM/>
    </Window.DataContext>

    <Window.Resources>
        <local:ComparisonConverter x:Key="ComparisonConverter"/>
    </Window.Resources>

    <StackPanel Orientation="Vertical">
        <RadioButton Content="강아지" IsChecked="{Binding SelectedAnimal, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:Animal.Dog}}"/>
        <RadioButton Content="고양이" IsChecked="{Binding SelectedAnimal, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:Animal.Cat}}"/>
        <RadioButton Content="돼지" IsChecked="{Binding SelectedAnimal, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:Animal.Pig}}"/>
        <TextBlock Text="{Binding SelectedAnimal}"/>
    </StackPanel>
</Window>

 

▶ 실행결과

WPF-RadioButton-Enum-Binding