How to bind RadioButtons to an enum?

前端 未结 9 2197
日久生厌
日久生厌 2020-11-22 03:21

I\'ve got an enum like this:

public enum MyLovelyEnum
{
    FirstSelection,
    TheOtherSelection,
    YetAnotherOne
};

I got a property in

9条回答
  •  臣服心动
    2020-11-22 04:05

    For UWP, it is not so simple: You must jump through an extra hoop to pass a field value as a parameter.

    Example 1

    Valid for both WPF and UWP.

    
        
            
                
                    Field
                
            
        
    
    

    Example 2

    Valid for both WPF and UWP.

    ...
    Field
    ...
    
    
    

    Example 3

    Valid only for WPF!

    
    

    UWP doesn't support x:Static so Example 3 is out of the question; assuming you go with Example 1, the result is more verbose code. Example 2 is slightly better, but still not ideal.

    Solution

    public abstract class EnumToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var Parameter = parameter as string;
    
            if (Parameter == null)
                return DependencyProperty.UnsetValue;
    
            if (Enum.IsDefined(typeof(TEnum), value) == false)
                return DependencyProperty.UnsetValue;
    
            return Enum.Parse(typeof(TEnum), Parameter).Equals(value);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            var Parameter = parameter as string;
            return Parameter == null ? DependencyProperty.UnsetValue : Enum.Parse(typeof(TEnum), Parameter);
        }
    }
    

    Then, for each type you wish to support, define a converter that boxes the enum type.

    public class MyEnumToBooleanConverter : EnumToBooleanConverter
    {
        //Nothing to do!
    }
    

    The reason it must be boxed is because there's seemingly no way to reference the type in the ConvertBack method; the boxing takes care of that. If you go with either of the first two examples, you can just reference the parameter type, eliminating the need to inherit from a boxed class; if you wish to do it all in one line and with least verbosity possible, the latter solution is ideal.

    Usage resembles Example 2, but is, in fact, less verbose.

    
    

    The downside is you must define a converter for each type you wish to support.

提交回复
热议问题