如何获取单选按钮组的引用并查找所选按钮?

5
使用以下XAML,我怎样才能在按钮的事件处理程序中获取对选定单选按钮的引用?
<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>
3个回答

7
最简单的方法就是给每个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,这是通过将项目模板化为绑定到ListBoxItemIsSelectedRadioButtons,然后将ListBox.SelectedItem绑定到属性来实现的。


谢谢回答。我看到了[这个答案1]。可能是打错了吗? - HerbalMart

1
如果您知道容器的ID,那么这种方法比接受的答案少了一些麻烦。
var radioButtons = LogicalTreeHelper.GetChildren(_myStackPanel).OfType<RadioButton>();
var selected = radioButtons.FirstOrDefault(x => (bool)x.IsChecked);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接