Simple WPF RadioButton Binding?

后端 未结 8 995
难免孤独
难免孤独 2020-12-12 16:00

What is the simplest way to bind a group of 3 radiobuttons to a property of type int for values 1, 2, or 3?

8条回答
  •  春和景丽
    2020-12-12 16:38

    I've come up with solution using Binding.DoNothing returned from converter which doesn't break two-way binding.

    public class EnumToCheckedConverter : IValueConverter
    {
        public Type Type { get; set; }
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value.GetType() == Type)
            {
                try
                {
                    var parameterFlag = Enum.Parse(Type, parameter as string);
    
                    if (Equals(parameterFlag, value))
                    {
                        return true;
                    }
                }
                catch (ArgumentNullException)
                {
                    return false;
                }
                catch (ArgumentException)
                {
                    throw new NotSupportedException();
                }
    
                return false;
            }
            else if (value == null)
            {
                return false;
            }
    
            throw new NotSupportedException();
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value is bool check)
            {
                if (check)
                {
                    try
                    {
                        return Enum.Parse(Type, parameter as string);
                    }
                    catch(ArgumentNullException)
                    {
                        return Binding.DoNothing;
                    }
                    catch(ArgumentException)
                    {
                        return Binding.DoNothing;
                    }
                }
    
                return Binding.DoNothing;
            }
    
            throw new NotSupportedException();
        }
    }
    

    Usage:

    
    

    Radio button bindings:

    Function
    

提交回复
热议问题