Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is my approach for binding a list of radio buttons to an enum.</p> <p>Using the Enum as a string in the button's Tag property, I use the <strong>Binding.Format</strong> and <strong>Binding.Parse</strong> event to decide which button should be checked.</p> <pre><code>public enum OptionEnum { Option1 = 0, Option2 } OptionEnum _rbEnum = OptionEnum.Option1; OptionEnum PropertyRBEnum { get { return _rbEnum; } set { _rbEnum = value; RaisePropertyChanged("PropertyRBEnum"); } } public static void FormatSelectedEnum&lt;T&gt;(object sender, ConvertEventArgs args) where T : struct { Binding binding = (sender as Binding); if (binding == null) return; Control button = binding.Control; if (button == null || args.DesiredType != typeof(Boolean)) return; T value = (T)args.Value; T controlValue; if (Enum.TryParse(button.Tag.ToString(), out controlValue)) { args.Value = value.Equals(controlValue); } else { Exception ex = new Exception("String not found in Enum"); ex.Data.Add("Tag", button.Tag); throw ex; } } public static void ParseSelectedEnum&lt;T&gt;(object sender, ConvertEventArgs args) where T : struct { Binding binding = (sender as Binding); if (binding == null) return; Control button = binding.Control; bool value = (bool)args.Value; if (button == null || value != true) return; T controlValue; if (Enum.TryParse(button.Tag.ToString(), out controlValue)) { args.Value = controlValue; } else { Exception ex = new Exception("String not found in Enum"); ex.Data.Add("Tag", button.Tag); throw ex; } } </code></pre> <p>Then setup your data binding like this:</p> <pre><code>radioButton1.Tag = "Option1"; radioButton2.Tag = "Option2"; foreach (RadioButtonUx rb in new RadioButtonUx[] { radioButton1, radioButton2 }) { Binding b = new Binding("Checked", this, "PropertyRBEnum"); b.Format += FormatSelectedRadioButton&lt;OptionEnum&gt;; b.Parse += ParseSelectedRadioButton&lt;OptionEnum&gt;; rb.DataBindings.Add(b); } </code></pre>
 

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