programing

RadioButtons를 열거형으로 바인드하는 방법

javajsp 2023. 4. 19. 22:16

RadioButtons를 열거형으로 바인드하는 방법

다음과 같은 정보가 있습니다.

public enum MyLovelyEnum
{
    FirstSelection,
    TheOtherSelection,
    YetAnotherOne
};

Data Context에 속성이 있습니다.

public MyLovelyEnum VeryLovelyEnum { get; set; }

내 WPF 클라이언트에 라디오 버튼 3개가 있어

<RadioButton Margin="3">First Selection</RadioButton>
<RadioButton Margin="3">The Other Selection</RadioButton>
<RadioButton Margin="3">Yet Another one</RadioButton>

적절한 양방향 바인딩을 위해 RadioButtons를 속성에 바인드하려면 어떻게 해야 하나요?

승인된 답변을 더욱 단순화할 수 있습니다.xaml에서 문자열로 enum을 입력하고 변환기에서 필요한 것보다 더 많은 작업을 수행하는 대신 문자열 표현 대신 열거 값을 명시적으로 전달할 수 있습니다. CrimsonX가 설명했듯이 오류는 실행 시간이 아닌 컴파일 시간에 발생합니다.

ConverterParameter={x: 정적 로컬:당신의 Enum Type.Enum1}

<StackPanel>
    <StackPanel.Resources>          
        <local:ComparisonConverter x:Key="ComparisonConverter" />          
    </StackPanel.Resources>
    <RadioButton IsChecked="{Binding Path=YourEnumProperty, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:YourEnumType.Enum1}}" />
    <RadioButton IsChecked="{Binding Path=YourEnumProperty, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:YourEnumType.Enum2}}" />
</StackPanel>

다음으로 컨버터를 심플하게 합니다.

public class ComparisonConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value?.Equals(parameter);
    }

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

편집(2010년 12월 16일):

Binding 반환을 제안해 주셔서 감사합니다.Dependency Property가 아닌 DoNothing.Unset Value(값 설정 해제)


참고 - 여러 그룹의 RadioButtons가 동일한 컨테이너에 포함되어 있습니다(2011년 2월 17일).

In xaml, if radio buttons share the same parent container, then selecting one will de-select all other's within that container (even if they are bound to a different property). So try to keep your RadioButton's that are bound to a common property grouped together in their own container like a stack panel. In cases where your related RadioButtons cannot share a single parent container, then set the GroupName property of each RadioButton to a common value to logically group them.

편집 (4월 5일 2011년):

Simplified ConvertBack's if-else to use a Ternary Operator.

참고 - 클래스에 중첩된 Enum 유형(Apr 28 '11):

If your enum type is nested in a class (rather than directly in the namespace), you might be able to use the '+' syntax to access the enum in XAML as stated in a (not marked) answer to the question :

ConverterParameter={x: 정적 로컬:Your Class + Your Nested Enum Type 。Enum1}

단, 이 Microsoft Connect 문제로 인해 VS2010의 설계자는 다음 명령어를 로드하지 않습니다."Type 'local:YourClass+YourNestedEnumType' was not found." 이 으로 실행됩니다.물론 열거 유형을 네임스페이스로 직접 이동할 수 있으면 이 문제를 방지할 수 있습니다.


편집(2012년 1월 27일):

If using Enum flags, the converter would be as follows:
public class EnumToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return ((Enum)value).HasFlag((Enum)parameter);
    }

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

편집 (15년 5월 7일) :

In case of a Nullable Enum (that is **not** asked in the question, but can be needed in some cases, e.g. ORM returning null from DB or whenever it might make sense that in the program logic the value is not provided), remember to add an initial null check in the Convert Method and return the appropriate bool value, that is typically false (if you don't want any radio button selected), like below:
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) {
            return false; // or return parameter.Equals(YourEnumType.SomeDefaultValue);
        }
        return value.Equals(parameter);
    }

주의 - NullReferenceException (18년 10월 10일):

Updated the example to remove the possibility of throwing a NullReferenceException. `IsChecked` is a nullable type so returning `Nullable` seems a reasonable solution.

보다 일반적인 변환기를 사용할 수 있습니다.

public class EnumBooleanConverter : IValueConverter
{
  #region IValueConverter Members
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string parameterString = parameter as string;
    if (parameterString == null)
      return DependencyProperty.UnsetValue;

    if (Enum.IsDefined(value.GetType(), value) == false)
      return DependencyProperty.UnsetValue;

    object parameterValue = Enum.Parse(value.GetType(), parameterString);

    return parameterValue.Equals(value);
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string parameterString = parameter as string;
    if (parameterString == null)
        return DependencyProperty.UnsetValue;

    return Enum.Parse(targetType, parameterString);
  }
  #endregion
}

XAML 부품에서는 다음을 사용합니다.

<Grid>
    <Grid.Resources>
      <l:EnumBooleanConverter x:Key="enumBooleanConverter" />
    </Grid.Resources>
    <StackPanel >
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
    </StackPanel>
</Grid>

Enum To Boolean Converter 응답의 경우:Dependency Property를 반환하는 대신.UnsetValue는 바인딩을 반환하는 것을 고려합니다.[DoNothing] : 옵션버튼의 [IsChecked]값이 false가 되는 경우전자는 문제를 나타내고(사용자에게 빨간 직사각형 또는 유사한 검증 인디케이터를 표시할 수 있습니다), 후자는 아무것도 하지 않는 것만을 나타냅니다.이 경우, 이것은 필요한 것입니다.

http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convertback.aspx http://msdn.microsoft.com/en-us/library/system.windows.data.binding.donothing.aspx

ListBox에서 RadioButtons를 사용하여 SelectedValue에 바인드합니다.

이것은 이 토픽에 관한 오래된 스레드입니다만, 기본적인 생각은 같습니다.http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/323d067a-efef-4c9f-8d99-fecf45522395/

UWP의 경우 다음과 같이 간단하지 않습니다.필드 값을 매개 변수로 전달하려면 추가 후프를 통과해야 합니다.

예 1

WPF와 UWP 모두에 유효합니다.

<MyControl>
    <MyControl.MyProperty>
        <Binding Converter="{StaticResource EnumToBooleanConverter}" Path="AnotherProperty">
            <Binding.ConverterParameter>
                <MyLibrary:MyEnum>Field</MyLibrary:MyEnum>
            </Binding.ConverterParameter>
        </MyControl>
    </MyControl.MyProperty>
</MyControl>

예 2

WPF와 UWP 모두에 유효합니다.

...
<MyLibrary:MyEnum x:Key="MyEnumField">Field</MyLibrary:MyEnum>
...

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={StaticResource MyEnumField}}"/>

예 3

WPF에만 유효!

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static MyLibrary:MyEnum.Field}}"/>

UWP를 지원하지 .x:Static따라서 예 3은 문제가 되지 않습니다. 1을 사용한다고 가정하면 결과는 보다 상세하게 표시됩니다. 2는 약간 낫지만 여전히 이상적이지 않습니다.

솔루션

public abstract class EnumToBooleanConverter<TEnum> : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var Parameter = parameter as string;

        if (Parameter == null)
            return DependencyProperty.UnsetValue;

        if (Enum.IsDefined(typeof(TEnum), value) == false)
            return DependencyProperty.UnsetValue;

        return Enum.Parse(typeof(TEnum), Parameter).Equals(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        var Parameter = parameter as string;
        return Parameter == null ? DependencyProperty.UnsetValue : Enum.Parse(typeof(TEnum), Parameter);
    }
}

그런 다음 지원하는 유형별로 열거형 상자에 넣을 변환기를 정의합니다.

public class MyEnumToBooleanConverter : EnumToBooleanConverter<MyEnum>
{
    //Nothing to do!
}

에 넣어야 는 겉으로 이 입니다.ConvertBack두 가지 예 중 경우 만 하면 됩니다에서 상속할 가 없습니다.한 것을 한 한 하고 이상적입니다.처음 두 가지 예 중 하나를 사용할 경우 파라미터 유형만 참조하면 됩니다.상자 클래스에서 상속할 필요가 없습니다.모든 것을 한 줄에 한 줄에 가능한 한 상세하게 설명하려면 후자의 솔루션이 이상적입니다.

사용법은 예 2와 비슷하지만 실제로는 덜 장황하다.

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource MyEnumToBooleanConverter}, ConverterParameter=Field}"/>

단점은 지원하는 유형별로 컨버터를 정의해야 한다는 것입니다.

RadioButtons와 CheckBoxes를 enums에 바인딩하기 위해 새 클래스를 만들었습니다.이 기능은 플래그가 있는 enum(복수의 체크박스가 있는 경우) 및 플래그가 없는 enum(싱글 선택 체크박스 또는 옵션버튼)에 대해 기능합니다.또한 Value Converters도 전혀 필요하지 않습니다.

처음에는 더 복잡해 보일 수 있지만 이 클래스를 프로젝트에 복사하면 완료됩니다.일반적이므로 모든 열거에 쉽게 재사용할 수 있습니다.

public class EnumSelection<T> : INotifyPropertyChanged where T : struct, IComparable, IFormattable, IConvertible
{
  private T value; // stored value of the Enum
  private bool isFlagged; // Enum uses flags?
  private bool canDeselect; // Can be deselected? (Radio buttons cannot deselect, checkboxes can)
  private T blankValue; // what is considered the "blank" value if it can be deselected?

  public EnumSelection(T value) : this(value, false, default(T)) { }
  public EnumSelection(T value, bool canDeselect) : this(value, canDeselect, default(T)) { }
  public EnumSelection(T value, T blankValue) : this(value, true, blankValue) { }
  public EnumSelection(T value, bool canDeselect, T blankValue)
  {
    if (!typeof(T).IsEnum) throw new ArgumentException($"{nameof(T)} must be an enum type"); // I really wish there was a way to constrain generic types to enums...
    isFlagged = typeof(T).IsDefined(typeof(FlagsAttribute), false);

    this.value = value;
    this.canDeselect = canDeselect;
    this.blankValue = blankValue;
  }

  public T Value
  {
    get { return value; }
    set 
    {
      if (this.value.Equals(value)) return;
      this.value = value;
      OnPropertyChanged();
      OnPropertyChanged("Item[]"); // Notify that the indexer property has changed
    }
  }

  [IndexerName("Item")]
  public bool this[T key]
  {
    get
    {
      int iKey = (int)(object)key;
      return isFlagged ? ((int)(object)value & iKey) == iKey : value.Equals(key);
    }
    set
    {
      if (isFlagged)
      {
        int iValue = (int)(object)this.value;
        int iKey = (int)(object)key;

        if (((iValue & iKey) == iKey) == value) return;

        if (value)
          Value = (T)(object)(iValue | iKey);
        else
          Value = (T)(object)(iValue & ~iKey);
      }
      else
      {
        if (this.value.Equals(key) == value) return;
        if (!value && !canDeselect) return;

        Value = value ? key : blankValue;
      }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void OnPropertyChanged([CallerMemberName] string propertyName = "")
  {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

사용방법에 대해서는 작업을 수동으로 또는 자동으로 실행하기 위한 열거형이 있으며, 요일별로 예약할 수 있으며 일부 옵션도 있다고 가정해 보겠습니다.

public enum StartTask
{
  Manual,
  Automatic
}

[Flags()]
public enum DayOfWeek
{
  Sunday = 1 << 0,
  Monday = 1 << 1,
  Tuesday = 1 << 2,
  Wednesday = 1 << 3,
  Thursday = 1 << 4,
  Friday = 1 << 5,
  Saturday = 1 << 6
}

public enum AdditionalOptions
{
  None = 0,
  OptionA,
  OptionB
}

다음은 이 클래스를 쉽게 사용할 수 있는 방법입니다.

public class MyViewModel : ViewModelBase
{
  public MyViewModel()
  {
    StartUp = new EnumSelection<StartTask>(StartTask.Manual);
    Days = new EnumSelection<DayOfWeek>(default(DayOfWeek));
    Options = new EnumSelection<AdditionalOptions>(AdditionalOptions.None, true, AdditionalOptions.None);
  }

  public EnumSelection<StartTask> StartUp { get; private set; }
  public EnumSelection<DayOfWeek> Days { get; private set; }
  public EnumSelection<AdditionalOptions> Options { get; private set; }
}

이 클래스에서 체크박스와 라디오 버튼을 쉽게 바인딩할 수 있습니다.

<StackPanel Orientation="Vertical">
  <StackPanel Orientation="Horizontal">
    <!-- Using RadioButtons for exactly 1 selection behavior -->
    <RadioButton IsChecked="{Binding StartUp[Manual]}">Manual</RadioButton>
    <RadioButton IsChecked="{Binding StartUp[Automatic]}">Automatic</RadioButton>
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <!-- Using CheckBoxes for 0 or Many selection behavior -->
    <CheckBox IsChecked="{Binding Days[Sunday]}">Sunday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Monday]}">Monday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Tuesday]}">Tuesday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Wednesday]}">Wednesday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Thursday]}">Thursday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Friday]}">Friday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Saturday]}">Saturday</CheckBox>
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <!-- Using CheckBoxes for 0 or 1 selection behavior -->
    <CheckBox IsChecked="{Binding Options[OptionA]}">Option A</CheckBox>
    <CheckBox IsChecked="{Binding Options[OptionB]}">Option B</CheckBox>
  </StackPanel>
</StackPanel>
  1. UI가 로드되면 "수동" 라디오 버튼이 선택되고 "수동" 또는 "자동" 중에서 선택을 변경할 수 있지만 항상 둘 중 하나를 선택해야 합니다.
  2. 요일마다 체크박스가 해제되지만 체크박스를 켜거나 끌 수 있는 요일 수 있습니다.
  3. 「Option A」와 「Option B」는 모두, 처음에는 오프가 됩니다.어느쪽인가를 체크할 수 있습니다.하나를 체크하면 다른 한쪽(RadioButtons와 유사)은 체크되지 않습니다.단, WPF의 RadioButton에서는 체크박스를 사용할 수 없습니다.

이것은 Checkbox에도 적용됩니다.

public class EnumToBoolConverter:IValueConverter
{
    private int val;
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int intParam = (int)parameter;
        val = (int)value;

        return ((intParam & val) != 0);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        val ^= (int)parameter;
        return Enum.Parse(targetType, val.ToString());
    }
}

단일 열거형을 여러 확인란에 바인딩합니다.

라디오 버튼을 동적으로 만들 수 있습니다.ListBox변환기를 사용하지 않고 매우 단순하게 작업을 수행할 수 있습니다.

구체적인 단계는 다음과 같습니다.

  • ListBox를 만들고 항목을 설정합니다.목록 상자의 열거형 원본MyLovelyEnum및 Selected의 바인드에 대한 ListBox 항목VeryLovelyEnum소유물.
  • 각 ListBoxItem의 라디오 버튼이 생성됩니다.
  • 순서 1: 윈도, 사용자 제어 또는 그리드 등의 정적 리소스에 열거형을 추가합니다.
    <Window.Resources>
        <ObjectDataProvider MethodName="GetValues"
                            ObjectType="{x:Type system:Enum}"
                            x:Key="MyLovelyEnum">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:MyLovelyEnum" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
  • 순서 2: 목록 상자를 사용하여Control Template각 항목을 라디오 버튼으로 채우다
    <ListBox ItemsSource="{Binding Source={StaticResource MyLovelyEnum}}" SelectedItem="{Binding VeryLovelyEnum, Mode=TwoWay}" >
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <RadioButton
                                Content="{TemplateBinding ContentPresenter.Content}"
                                IsChecked="{Binding Path=IsSelected,
                                RelativeSource={RelativeSource TemplatedParent},
                                Mode=TwoWay}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.Resources>
    </ListBox>

장점은 언젠가 열거 클래스가 변경될 경우 GUI(XAML 파일)를 업데이트할 필요가 없다는 것입니다.

참고 자료: https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/

이 문제를 해결하는 한 가지 방법은 당신의 Bool 속성에 별도의 속성을 갖는 것입니다.ViewModel이런 상황에서 어떻게 대처했는지는 다음과 같습니다.

뷰 모델:

public enum MyLovelyEnum { FirstSelection, TheOtherSelection, YetAnotherOne };
private MyLovelyEnum CurrentSelection;

public bool FirstSelectionProperty
{
    get
    {
        return CurrentSelection == MyLovelyEnum.FirstSelection;
    }
    set
    {
        if (value)
            CurrentSelection = MyLovelyEnum.FirstSelection;
    }
}

public bool TheOtherSelectionProperty
{
    get
    {
        return CurrentSelection == MyLovelyEnum.TheOtherSelection;
    }
    set
    {
        if (value)
            CurrentSelection = MyLovelyEnum.TheOtherSelection;
    }
}

public bool YetAnotherOneSelectionProperty
{
    get
    {
        return CurrentSelection == MyLovelyEnum.YetAnotherOne;
    }
    set
    {
        if (value)
            CurrentSelection = MyLovelyEnum.YetAnotherOne;
    }
}

XAML:

<RadioButton IsChecked="{Binding SimilaritySort, Mode=TwoWay}">Similarity</RadioButton>
<RadioButton IsChecked="{Binding DateInsertedSort, Mode=TwoWay}">Date Inserted</RadioButton>
<RadioButton IsChecked="{Binding DateOfQuestionSort, Mode=TwoWay}">Date of Question</RadioButton>
<RadioButton IsChecked="{Binding DateModifiedSort, Mode=TwoWay}">Date Modified</RadioButton>

다른 솔루션만큼 견고하거나 동적이지는 않지만, 뛰어난 점은 매우 자기 완비되어 있어 커스텀 컨버터 등을 작성할 필요가 없다는 것입니다.

Scott의 EnumToBoolean Converter에 기반합니다.ConvertBack 메서드는 Enum with flags 코드에서는 작동하지 않습니다.

다음 코드를 시도했습니다.

public class EnumHasFlagToBooleanConverter : IValueConverter
    {
        private object _obj;
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            _obj = value;
            return ((Enum)value).HasFlag((Enum)parameter);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value.Equals(true))
            {
                if (((Enum)_obj).HasFlag((Enum)parameter))
                {
                    // Do nothing
                    return Binding.DoNothing;
                }
                else
                {
                    int i = (int)_obj;
                    int ii = (int)parameter;
                    int newInt = i+ii;
                    return (NavigationProjectDates)newInt;
                }
            }
            else
            {
                if (((Enum)_obj).HasFlag((Enum)parameter))
                {
                    int i = (int)_obj;
                    int ii = (int)parameter;
                    int newInt = i-ii;
                    return (NavigationProjectDates)newInt;

                }
                else
                {
                    // do nothing
                    return Binding.DoNothing;
                }
            }
        }
    }

내가 일할 수 없는 유일한 것은 내가 할 수 있는 일은int로.targetType그래서 하드코딩을 해서NavigationProjectDates, 내가 사용하는 열거형.그리고.targetType == NavigationProjectDates...


보다 일반적인 플래그 열거형 변환기에 대해 편집:

퍼블릭 클래스 Flags Enum To Boolean Converter : IValue Converter {개인 int _private=0;public object Convert(개체값, Type target)유형, 개체 매개 변수, 문자열 언어) {(값 == null)이 false를 반환하는 경우,_syslog = (int) 값;t = 값을 입력합니다.GetType();object o = Enum.ToObject(t, 파라미터);
(Enum) 값을 반환합니다.HasFlag((Enum)o);
}
공용 객체 ConvertBack(개체 값, Type target)유형, 객체 파라미터, 문자열 언어){if(가치)동등(진짜)?false) {_syslog = _syslog | (int) 파라미터;}그렇지 않으면 {_param = _parameter & ~(int) 파라미터;}반환_복귀;}}

Nullable을 사용하는 UWP에 대한 양방향 바인딩 솔루션:

C# 부품:

public class EnumConverter : IValueConverter
{
    public Type EnumType { get; set; }
    public object Convert(object value, Type targetType, object parameter, string lang)
    {
        if (parameter is string enumString)
        {
            if (!Enum.IsDefined(EnumType, value)) throw new ArgumentException("value must be an Enum!");
            var enumValue = Enum.Parse(EnumType, enumString);
            return enumValue.Equals(value);
        }
        return value.Equals(Enum.ToObject(EnumType,parameter));
    }

    public object ConvertBack(object value, Type targetType, object parameter, string lang)
    {
        if (parameter is string enumString)
            return value?.Equals(true) == true ? Enum.Parse(EnumType, enumString) : null;
        return value?.Equals(true) == true ? Enum.ToObject(EnumType, parameter) : null;
    }
}

★★★★★★★★★★★★★★★★★★.null는 Bindingvalue Binding으로 합니다.DoNothing(「DoNothing」)

private YourEnum? _yourEnum = YourEnum.YourDefaultValue; //put a default value here
public YourEnum? YourProperty
{
    get => _yourEnum;
    set{
        if (value == null) return;
        _yourEnum = value;
    }
}

Xaml 부품:

...
<Page.Resources>
    <ResourceDictionary>
        <helper:EnumConverter x:Key="YourConverter" EnumType="yournamespace:YourEnum" />
    </ResourceDictionary>
</Page.Resources>
...
<RadioButton GroupName="YourGroupName" IsChecked="{Binding Converter={StaticResource YourConverter}, Mode=TwoWay, Path=YourProperty, ConverterParameter=YourEnumString}">
    First way (parameter of type string)
</RadioButton>
<RadioButton GroupName="LineWidth">
    <RadioButton.IsChecked>
        <Binding
            Converter="{StaticResource PenWidthConverter}"
            Mode="TwoWay"   Path="PenWidth">
            <Binding.ConverterParameter>
                <yournamespace:YourEnum>YourEnumString</yournamespace:YourEnum>
            </Binding.ConverterParameter>
        </Binding>
    </RadioButton.IsChecked>
    Second way (parameter of type YourEnum (actually it was converted to int when passed to converter))
</RadioButton>

언급URL : https://stackoverflow.com/questions/397556/how-to-bind-radiobuttons-to-an-enum