Determining checked Radiobutton from groupbox in WPF following MVVM

后端 未结 5 1788
有刺的猬
有刺的猬 2021-02-05 13:44

I have a groupbox with some radiobuttons. How do I get to know which one which is checked? I am using WPF and following MVVM.



        
5条回答
  •  心在旅途
    2021-02-05 14:14

    If you use Tag property on options buttons (boolean, integer, strings) like in his XAML

    
        
        
        
        
    
    

    Then you can use following function to get selected value (button)

    int priority = SelectedRadioValue(0, rP0, rP1, rP2, rP3);
    

    where

    public T SelectedRadioValue(T defaultValue, params RadioButton[] buttons)
    {
        foreach (RadioButton button in buttons)
        {
            if (button.IsChecked == true)
            {
                if (button.Tag is string && typeof(T) != typeof(string))
                {
                    string value = (string) button.Tag;
                    return (T) Convert.ChangeType(value, typeof(T));
                }
    
                return (T)button.Tag;
            }
        }
    
        return defaultValue;
    }
    

提交回复
热议问题