【问题标题】:How can I get a reference to a group of radiobuttons and find the selected one?如何获得对一组单选按钮的引用并找到选定的单选按钮?
【发布时间】:2012-03-12 20:47:07
【问题描述】:
如何使用以下 XAML 在 Button 的事件处理程序中获取对选定单选按钮的引用?
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="myWindow">
<Grid>
<StackPanel>
<RadioButton Content="A" GroupName="myGroup"></RadioButton>
<RadioButton Content="B" GroupName="myGroup"></RadioButton>
<RadioButton Content="C" GroupName="myGroup"></RadioButton>
</StackPanel>
<Button Click="Button_Click" Height="100" Width="100"></Button>
</Grid>
</Window>
【问题讨论】:
标签:
wpf
xaml
radio-button
selecteditem
【解决方案1】:
最简单的方法是为每个 RadioButton 命名,并测试其 IsChecked 属性。
<RadioButton x:Name="RadioButtonA" Content="A" GroupName="myGroup"></RadioButton>
<RadioButton x:Name="RadioButtonB" Content="B" GroupName="myGroup"></RadioButton>
<RadioButton x:Name="RadioButtonC" Content="C" GroupName="myGroup"></RadioButton>
if (RadioButtonA.IsChecked) {
...
} else if (RadioButtonB.IsChecked) {
...
} else if (RadioButtonC.IsChecked) {
...
}
但是使用 Linq 和逻辑树可以让它不那么冗长:
myWindow.FindDescendants<CheckBox>(e => e.IsChecked).FirstOrDefault();
FindDescendants 是一个可重用的扩展方法:
public static IEnumerable<T> FindDescendants<T>(this DependencyObject parent, Func<T, bool> predicate, bool deepSearch = false) where T : DependencyObject {
var children = LogicalTreeHelper.GetChildren(parent).OfType<DependencyObject>().ToList();
foreach (var child in children) {
var typedChild = child as T;
if ((typedChild != null) && (predicate == null || predicate.Invoke(typedChild))) {
yield return typedChild;
if (deepSearch) foreach (var foundDescendant in FindDescendants(child, predicate, true)) yield return foundDescendant;
} else {
foreach (var foundDescendant in FindDescendants(child, predicate, deepSearch)) yield return foundDescendant;
}
}
yield break;
}
【解决方案2】:
您可以使用ListBox,如this answer 所示,这是通过将RadioButtons 绑定到ListBoxItem 的IsSelected 然后将ListBox.SelectedItem 绑定到属性来实现的。
【解决方案3】:
如果您知道容器的 ID,则比公认的答案要少一点:
var radioButtons = LogicalTreeHelper.GetChildren(_myStackPanel).OfType<RadioButton>();
var selected = radioButtons.FirstOrDefault(x => (bool)x.IsChecked);