Simple WPF RadioButton Binding?

后端 未结 8 990
难免孤独
难免孤独 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:55

    I created an attached property based on Aviad's Answer which doesn't require creating a new class

    public static class RadioButtonHelper
    {
        [AttachedPropertyBrowsableForType(typeof(RadioButton))]
        public static object GetRadioValue(DependencyObject obj) => obj.GetValue(RadioValueProperty);
        public static void SetRadioValue(DependencyObject obj, object value) => obj.SetValue(RadioValueProperty, value);
        public static readonly DependencyProperty RadioValueProperty =
            DependencyProperty.RegisterAttached("RadioValue", typeof(object), typeof(RadioButtonHelper), new PropertyMetadata(new PropertyChangedCallback(OnRadioValueChanged)));
    
        private static void OnRadioValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is RadioButton rb)
            {
                rb.Checked -= OnChecked;
                rb.Checked += OnChecked;
            }
        }
    
        public static void OnChecked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton rb)
            {
                rb.SetCurrentValue(RadioBindingProperty, rb.GetValue(RadioValueProperty));
            }
        }
    
        [AttachedPropertyBrowsableForType(typeof(RadioButton))]
        public static object GetRadioBinding(DependencyObject obj) => obj.GetValue(RadioBindingProperty);
        public static void SetRadioBinding(DependencyObject obj, object value) => obj.SetValue(RadioBindingProperty, value);
    
        public static readonly DependencyProperty RadioBindingProperty =
            DependencyProperty.RegisterAttached("RadioBinding", typeof(object), typeof(RadioButtonHelper), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnRadioBindingChanged)));
    
        private static void OnRadioBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is RadioButton rb && rb.GetValue(RadioValueProperty).Equals(e.NewValue))
            {
                rb.SetCurrentValue(RadioButton.IsCheckedProperty, true);
            }
        }
    }
    

    usage :

    
    
    
    
    

提交回复
热议问题