2012-02-09 15 views
13

Imaginemos que tengo:radiobuttons vinculantes grupo a una propiedad en WPF

<RadioButton GroupName="Group1" IsChecked="{Binding Path=RadioButton1IsChecked}" /> 
<RadioButton GroupName="Group1" IsChecked="{Binding Path=RadioButton2IsChecked}" /> 

Y luego, en mi clase de fuente de datos que tengo:

public bool RadioButton1IsChecked { get; set; } 
public bool RadioButton2IsChecked { get; set; } 
public enum RadioButtons { RadioButton1, RadioButton2, None } 
public RadioButtons SelectedRadioButton 
{ 
    get 
    { 
     if (this.RadioButtonIsChecked) 
      return RadioButtons.RadioButton1; 
     else if (this.RadioButtonIsChecked) 
      return RadioButtons.RadioButton2; 
     else 
      return RadioButtons.None; 
    } 
} 

¿hay algún modo unir mis botones de radio directamente a SelectedRadioButton propiedad? Realmente necesito las propiedades RadioButton1IsChecked y RadioButton2IsChecked solo para calcular el botón de radio seleccionado.

+0

esta [publicación de blog] (http://blogs.msdn.com/b/mthalman/archive/2008/09/04/wpf-data-binding-with-radiobutton.aspx) puede ayudar –

+0

Ver [mi respuesta en una pregunta relacionada] (http://stackoverflow.com/questions/9145606/how-can-i-reduce-this-wpf-boilerplate-code/9145914#9145914), debería ayudar. El 'SelectedItem' se une a la propiedad de interés. –

+3

Prefiero: http://stackoverflow.com/questions/397556/how-to-bind-radiobuttons-to-an-enum – quetzalcoatl

Respuesta

15
<RadioButton GroupName="Group1" IsChecked="{Binding Path=SelectedRadioButton, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=RadioButton1}" /> 
<RadioButton GroupName="Group1" IsChecked="{Binding Path=SelectedRadioButton, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=RadioButton2}" /> 
public enum RadioButtons { RadioButton1, RadioButton2, None } 
public RadioButtons SelectedRadioButton {get;set;} 

public class EnumBooleanConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      var ParameterString = parameter as string; 
      if (ParameterString == null) 
       return DependencyProperty.UnsetValue; 

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

      object paramvalue = Enum.Parse(value.GetType(), ParameterString); 
      return paramvalue.Equals(value); 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      var ParameterString = parameter as string; 
      var valueAsBool = (bool) value; 

      if (ParameterString == null || !valueAsBool) 
      { 
       try 
       { 
        return Enum.Parse(targetType, "0"); 
       } 
       catch (Exception) 
       { 
        return DependencyProperty.UnsetValue; 
       } 
      } 
      return Enum.Parse(targetType, ParameterString); 
     } 
    } 
+0

¿Esto no establecería el valor 'SelectedRadioButton' en' RadioButtons.None '(ejecutando' return Enum.Parse (targetType, "0"); ') siempre que alguna de las propiedades de los botones de opción" IsChecked "se establezca en' false'? –

21

Declarar una enumeración similar a:

enum RadioOptions {Option1, Option2} 

XAML:

<RadioButton IsChecked="{Binding SelectedOption, Converter={StaticResource EnumBooleanConverter}, ConverterParameter={x:Static local:RadioOptions.Option1}}"/> 
<RadioButton IsChecked="{Binding SelectedOption, Converter={StaticResource EnumBooleanConverter}, ConverterParameter={x:Static local:RadioOptions.Option2}}"/> 

clase Convertidor:

public class EnumBooleanConverter : 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 ((bool)value) ? parameter : Binding.DoNothing; 
    } 
} 
+0

¿Cuál es la diferencia funcional con la respuesta aceptada? – Jerther

+2

@Jerther: la respuesta aceptada toma un parámetro de cadena y lo convierte en una enumeración. Éste acepta directamente un valor enum, que es una idea mucho mejor, ya que no podrá compilarse si un parámetro es incorrecto. – Artfunkel

-1

XAML:

<RadioButton IsChecked="{Binding Path=SelectedOption, UpdateSourceTrigger=PropertyChanged}">Option1</RadioButton> 
<RadioButton IsChecked="{Binding Path=SelectedOption, UpdateSourceTrigger=PropertyChanged, Converter={v:NotBoolenConverter}}">Option2</RadioButton> 

Convertidor:

public class NotBoolenConverter : IValueConverter 
    { 
     public NotBoolenConverter() 
     { 
     } 

     public override object Convert(
      object value, 
      Type targetType, 
      object parameter, 
      CultureInfo culture) 
     { 
      bool output = (bool)value; 
      return !output; 
     } 

     public override object ConvertBack(
      object value, 
      Type targetType, 
      object parameter, 
      CultureInfo culture) 
     { 
      bool output = (bool)value; 
      return !output; 
     } 
    } 

Funciona con 2 botones de radio, por unirlas una con el opuesto del otro.

Cuestiones relacionadas