我正在努力学习如何更有效地使用复选框,我发现这个例子是关于如何完成我想要完成的事情,但我不想在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"/>
所以它做的是检查所有3,如果选中1,
如何使用C#代码完成此操作。
答案 0 :(得分:0)
将所有这些复选框放在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;
}
}
}
}
答案 1 :(得分:0)
以下是一个例子:
<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;
}
}
}
}
}
}
USE CASE:如果选中一个,则全部三个
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;
}
}
}