2013-06-13 3 views
1

У меня есть ссылка на RadioButton rb1.
Как я могу получить индекс выбранного RadioButton в группе rb1?
У меня есть googled какое-то время, но безуспешно.Получение индекса выбранного RadioButton в группе

Любая помощь будет принята с благодарностью

+2

Что вы пытаетесь достичь? Я не могу представить вариант использования, где вам это нужно. – WiiMaxx

ответ

0

Если вы добрались до этой точки, то есть, вероятно, что-то не так с вашим дизайном, и вы должны его пересмотреть.

что сказанное можно пройти визуальное дерево и найти его, как это:

 /// Returns the first GroupBox ancester    
     public DependencyObject FindAncestor(DependencyObject current) 

     { 
      current = VisualTreeHelper.GetParent(current); 

      while (current != null) 
      { 
       if (current is GroupBox) 
       { 
        return (T)current; 
       } 
       current = VisualTreeHelper.GetParent(current); 
      }; 
      return null; 
     } 

затем над детьми и найти проверенного RadioButton

public RadioButton FindChild<T>(DependencyObject parent)  
    { 
     // Confirm parent and childName are valid. 
     if (parent == null) return null; 

     RadioButton foundChild = null; 

     int childrenCount = VisualTreeHelper.GetChildrenCount(parent); 
     for (int i = 0; i < childrenCount; i++) 
     { 
      var child = VisualTreeHelper.GetChild(parent, i); 
      // If the child is not of the request child type child 
      var childType = child as radioButton; 
      if (childType == null) 
      { 
       // recursively drill down the tree 
       foundChild = FindChild(child); 

       // If the child is found, break so we do not overwrite the found child. 
       if (foundChild != null) return foundChild ; 
      } 
      else if (childName.IsChecked == true) 
      { 
       return foundChild; 
      } 
     } 

     return null; 
    } 
0

Ну короткий ответ на ваш вопрос вы этого не делаете. То, что вы должны сделать, это связать RadioButton.IsChecked с некоторым bool свойства вашего вида модели. Вы можете достичь что-то вроде индекса группы пути связывания int свойства вашей модели с помощью вашей реализации IValueConverter:

вида Модели недвижимости:

private int _groupIndex = 1; 

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

Преобразователь:

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; 
    } 
} 

, а затем вам привязать его например:

<StackPanel Orientation="Horizontal"> 
    <StackPanel.Resources> 
     <local:IndexBooleanConverter x:Key="IndexBooleanConverter"/> 
    </StackPanel.Resources> 
    <RadioButton Content="Option1" IsChecked="{Binding Path=GroupIndex, Converter={StaticResource IndexBooleanConverter}, ConverterParameter=1}"/> 
    <RadioButton Content="Option2" IsChecked="{Binding Path=GroupIndex, Converter={StaticResource IndexBooleanConverter}, ConverterParameter=2}"/> 
    <RadioButton Content="Option3" IsChecked="{Binding Path=GroupIndex, Converter={StaticResource IndexBooleanConverter}, ConverterParameter=3}"/> 
</StackPanel> 

В этом случае ваше свойство модели просмотра GroupIndex будет иметь значения 1, 2 или 3 в зависимости от того, что отмечено RadioButton

Смежные вопросы