如何获得一组radiobuttons的参考并找到所选的一个?

时间:2012-02-22 13:58:23

标签: wpf xaml radio-button selecteditem

使用以下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>

3 个答案:

答案 0 :(得分:6)

最简单的方法是为每个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和Logical Tree可以使它更简洁:

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

答案 1 :(得分:1)

您可以使用this answer中显示的ListBox,这可以通过模板绑定到RadioButtons IsSelected的项ListBoxItem来实现。然后将ListBox.SelectedItem绑定到属性。

答案 2 :(得分:0)

如果您知道容器的ID,则比接受的答案少一些毛病:

var radioButtons = LogicalTreeHelper.GetChildren(_myStackPanel).OfType<RadioButton>();
var selected = radioButtons.Where(x => (bool)x.IsChecked).FirstOrDefault();