2012-02-22 23 views
4

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

回答

4

最简单的方法是给每个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; 
    } 
+0

非常优雅的解决方案!谢谢! – lightxx 2013-04-03 07:12:06

1

可以使用ListBox如图this answer,这部作品通过模板化的项目是RadioButtons绑定到ListBoxItemIsSelected然后结合ListBox.SelectedItem一个属性。

+0

谢谢回答。我看到[这个答案1]。可能是一个错字? – HerbalMart 2012-02-22 14:21:53

+0

@HerbalMart:Woops,固定。 – 2012-02-22 14:27:02

相关问题