一次检查所有的复选框,但不是在XAML中
本文关键字:XAML 复选框 一次 检查 | 更新日期: 2023-09-27 18:04:19
我想学习如何更有效地使用复选框,我发现这个例子如何完成一些我想完成,但我不想在XAML中做的事情。
<CheckBox Content="Do Everything" IsChecked="{Binding DoEverything}" IsThreeState="True"/>
<CheckBox Content="Eat" IsChecked="{Binding DoEat}" Margin="20,0,0,0"/>
<CheckBox Content="Pray" IsChecked="{Binding DoPray}" Margin="20,0,0,0"/>
<CheckBox Content="Love" IsChecked="{Binding DoLove}" Margin="20,0,0,0"/>
如果选中了1,它会检查所有3个
我如何做到这一点,但与c#代码。
把所有这些复选框放到一个staklayout上,并给它一个名字,让它是Container
则按如下方式处理Do everything
检查事件:
void check_CheckedChanged(object sender, EventArgs e)
{
CheckBox senderCheck = sender as CheckBox;
if (senderCheck.Checked)
{
foreach (var c in Container.Children)
{
CheckBox check = c as CheckBox;
if (check != null)
{
if (radio.Id != senderCheck.Id)
check.Checked = true;
}
}
}
}
下面是一个例子:
<Window x:Class="WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-commpatibility/2006"
xmlns:local="clr-namespace:WPFXamDataGrid"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<StackPanel x:Name="Container">
<CheckBox Content="Do Everything" IsThreeState="True"/>
<CheckBox Content="Eat" Margin="20,0,0,0"/>
<CheckBox Content="Pray" Margin="20,0,0,0"/>
<CheckBox Content="Love" Margin="20,0,0,0"/>
</StackPanel>
</Grid>
</Window>
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (CheckBox check in FindVisualChildren<CheckBox>(Container))
{
// you can create your cases here
// my case is all checkboxes checked
check.IsChecked = true;
}
}
public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T) child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
}
}
用例:如果选中了一个,则所有三个
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (CheckBox check in FindVisualChildren<CheckBox>(Container))
{
if (check.IsChecked)
{
foreach (CheckBox check1 in FindVisualChildren<CheckBox>(Container))
{
check1.IsChecked = true;
}
break;
}
}
}