将radiobuttons绑定到WPF中的属性

Bog*_*ets 22 wpf binding radio-group radio-button

让我们想象我有:

<RadioButton GroupName="Group1" IsChecked="{Binding Path=RadioButton1IsChecked}" />
<RadioButton GroupName="Group1" IsChecked="{Binding Path=RadioButton2IsChecked}" />
Run Code Online (Sandbox Code Playgroud)

然后在我的数据源类中,我有:

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;
     }
}
Run Code Online (Sandbox Code Playgroud)

我可以以某种方式将我的单选按钮直接绑定到SelectedRadioButton属性吗?我真的只需要RadioButton1IsCheckedRadioButton2IsChecked属性来计算选定的单选按钮.

Usm*_*far 42

声明类似于的枚举:

enum RadioOptions {Option1, Option2}
Run Code Online (Sandbox Code Playgroud)

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}}"/>
Run Code Online (Sandbox Code Playgroud)

转换器类:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Jerther:接受的答案采用字符串参数并将其转换为枚举.这个直接接受枚举值,这是一个更好的主意,因为如果参数不正确将无法编译. (4认同)

Bog*_*ets 18

<RadioButton GroupName="Group1" IsChecked="{Binding Path=SelectedRadioButton, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=RadioButton1}" />
<RadioButton GroupName="Group1" IsChecked="{Binding Path=SelectedRadioButton, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=RadioButton2}" />
Run Code Online (Sandbox Code Playgroud)
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);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Bra*_*ung 5

我们可以动态创建单选按钮,ListBox可以帮助我们做到这一点,无需转换器,非常简单。

优点如下:如果有一天您的枚举类发生更改,您不需要更新 GUI(XAML 文件)。

步骤如下:创建一个ListBox,并将列表框的ItemsSource设置为枚举,并将ListBox的SelectedItem绑定到Selected属性。然后将创建每个 ListBoxItem 的单选按钮。

public enum RadioButtons
{ 
   RadioButton1, 
   RadioButton2, 
   None
}
Run Code Online (Sandbox Code Playgroud)
  • 第 1 步:将枚举添加到窗口、用户控件或网格等的静态资源中。
    <Window.Resources>
        <ObjectDataProvider MethodName="GetValues"
                            ObjectType="{x:Type system:Enum}"
                            x:Key="RadioButtons">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:RadioButtons" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
Run Code Online (Sandbox Code Playgroud)
  • 第 2 步:使用列表框并将Control Template每个项目填充为单选按钮
    <ListBox ItemsSource="{Binding Source={StaticResource RadioButtons}}" SelectedItem="{Binding SelectedRadioButton, 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>
Run Code Online (Sandbox Code Playgroud)

现在,尽情享受吧~

参考文献: https ://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/