gpt4 book ai didi

wpf - 如何获得对一组单选按钮的引用并找到所选的单选按钮?

转载 作者:行者123 更新时间:2023-12-04 14:22:38 25 4
gpt4 key购买 nike

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

最佳答案

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

关于wpf - 如何获得对一组单选按钮的引用并找到所选的单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9396239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com