具有3个RadioButton的单个属性并且未正确更新

时间:2017-04-12 08:49:49

标签: wpf xaml

我有一个场景,我为一组单选按钮保留了三个不同的属性是否可以将其设为单个?

<RadioButton GroupName="os" IsChecked="{Binding Age} IsChecked="{Binding Name,Mode=TwoWay,Converter={StaticResource enumConverter},ConverterParameter=a}"/>
<RadioButton GroupName="os" IsChecked="{Binding Age,Mode=TwoWay,Converter={StaticResource enumConverter},ConverterParameter=b}"/>
<RadioButton GroupName="os" IsChecked="{Binding Age,Mode=TwoWay,Converter={StaticResource enumConverter},ConverterParameter=c}"/>

这里我需要编写一个StringConverter,我将把转换器参数作为A,B,C传递给各个单选按钮。

 public class EnumMatchToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        if (value == null || parameter == null)
            return false;

        //string checkValue = value.ToString();
        //string targetValue = parameter.ToString();
        //return checkValue.Equals(targetValue,
        //         StringComparison.InvariantCultureIgnoreCase);
        if (value.ToString() == "True" && (parameter.ToString() == "a" || parameter.ToString() == "b" || parameter.ToString() == "c"))
        {
            return true;
        }
        else
            return false;
    }

    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
        if (value == null || parameter == null)
        return null;

        //bool useValue = (bool)value;
        //string targetValue = parameter.ToString();
        //if (useValue)
        //    return Enum.Parse(targetType, targetValue);

        //return null; 

        if (value.ToString() == "True" && (parameter.ToString() == "b" || parameter.ToString() == "a" || parameter.ToString() == "c"))
        {
            return true;
        }
        else
            return false;

    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

public class EnumMatchToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || parameter == null)
            return false;

        return value.ToString() == parameter.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool isChecked = (bool)value;
        if (isChecked)
            return parameter.ToString();

        return Binding.DoNothing;

    }
}

您可能还想考虑将转换器类重命名为更合适的类型。