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 > 개발' 카테고리의 다른 글
WPF ItemsControl HorizontalScrollBar 활성화 방법 (0) | 2024.08.12 |
---|---|
WPF 프로세스 아이콘 가져오는 방법 (0) | 2024.07.25 |
WPF ListBox 아이템 간격 설정하는 방법 (0) | 2024.04.12 |
WPF Button Image Background 없애는 방법 (0) | 2024.04.04 |
WPF enum DataTrigger Binding 하는 방법 (0) | 2024.02.07 |