Csharp/C#教程:获取组中所选RadioButton的索引分享


获取组中所选RadioButton的索引

我有一个RadioButton rb1的引用。
如何在rb1的组中获取所选RadioButton的索引?
我用Google搜索了一段时间但没有成功。

任何帮助将不胜感激

如果你到了这一点,那么你的设计可能有问题,你应该重新考虑它。

据说你可以遍历视觉树并找到它:

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

你的问题很简短,你不是。 你应该做的是将RadioButton.IsChecked绑定到视图模型的某个bool属性。 您可以通过IValueConverter的实现IValueConverter视图模型的int属性来实现组索引之类的操作:

查看模型属性:

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

然后你像这样绑定它:

         

在这种情况下,视图模型属性GroupIndex将具有值1,2或3,具体取决于选中的RadioButton

上述就是C#学习教程:获取组中所选RadioButton的索引分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/959974.html

(0)
上一篇 2021年11月24日
下一篇 2021年11月24日

精彩推荐