Getting the index of the selected RadioButton in a group

前端 未结 2 1007
慢半拍i
慢半拍i 2020-12-20 03:55

I have got a reference to a RadioButton rb1.
How can I get the index of the selected RadioButton in rb1\'s group ?
I have googled for a while but without success.

2条回答
  •  醉梦人生
    2020-12-20 04:29

    Well short answer to your question is you don't. What you should do is bind RadioButton.IsChecked to some boolproperty of your view model. You can achieve something like group index by binding int property of your view model via your implementation of IValueConverter:

    View Model property:

    private int _groupIndex = 1;
    
    public int GroupIndex
    {
       get { return _groupIndex; }
       set
       {
           if (_groupIndex == value) return;
           _groupIndex = value;
           OnPropertyChanged("GroupIndex");
       }
    }
    

    Converter:

    public class IndexBooleanConverter : IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
          if (value == null || parameter == null)
              return false;
          else
              return (int)value == System.Convert.ToInt32(parameter);
      }
    
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
          if (value == null || parameter == null)
              return null;
          else if ((bool)value)
              return System.Convert.ToInt32(parameter);
          else
              return DependencyProperty.UnsetValue;
      }
    }   
    

    and then you bind it like this:

    
       
           
       
       
       
       
    
    

    In this case your view model property GroupIndex will have values 1, 2 or 3 depending on what RadioButton is ticked

提交回复
热议问题