Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've done this through a <code>ValueConverter</code> that converts an <code>enum</code> to a <code>bool</code>. By passing the enum value that your radio button represents as the <code>ConverterParameter</code>, the converter returns whether this radio button should be checked or not.</p> <pre><code>&lt;Window.Resources&gt; &lt;Converters:EnumConverter x:Key="EnumConverter" /&gt; &lt;/Window.Resources&gt; &lt;RadioButton IsChecked="{Binding Path=MyEnum, Mode=TwoWay, Converter={StaticResource EnumConverter}, ConverterParameter=Enum1}"} Content="Enum 1" /&gt; &lt;RadioButton IsChecked="{Binding Path=MyEnum, Mode=TwoWay, Converter={StaticResource EnumConverter}, ConverterParameter=Enum2}"} Content="Enum 2" /&gt; </code></pre> <p><code>EnumConverter</code> is defined as follows:</p> <pre><code>public class EnumConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (targetType.IsAssignableFrom(typeof(Boolean)) &amp;&amp; targetType.IsAssignableFrom(typeof(String))) throw new ArgumentException("EnumConverter can only convert to boolean or string."); if (targetType == typeof(String)) return value.ToString(); return String.Compare(value.ToString(), (String)parameter, StringComparison.InvariantCultureIgnoreCase) == 0; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (targetType.IsAssignableFrom(typeof(Boolean)) &amp;&amp; targetType.IsAssignableFrom(typeof(String))) throw new ArgumentException("EnumConverter can only convert back value from a string or a boolean."); if (!targetType.IsEnum) throw new ArgumentException("EnumConverter can only convert value to an Enum Type."); if (value.GetType() == typeof(String)) { return Enum.Parse(targetType, (String)value, true); } //We have a boolean, as for binding to a checkbox. we use parameter if ((Boolean)value) return Enum.Parse(targetType, (String)parameter, true); return null; } } </code></pre> <p>Note that I don't databind to the list of enums to generate the radio buttons, I've done them by hand. If you wanted to fill the list of radio buttons through a binding, I think you'll need to change the <code>IsChecked</code> binding to a <code>MultiBinding</code> which binds to both the current value and the radio's enum value, because you cannot use a binding on <code>ConverterParameter</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload