如何通过单击一个按钮并仅使用 XAML 来选中或取消选中每个 CheckBox?

How can I check or uncheck every CheckBox with one Click on one Button and only with XAML?

所以我有 5 个 CheckBox,并且希望在单击一个 Button 时在每个 CheckBox 上获得不同的 Check 状态。因此,当我的 CheckBoxes 未选中并且我单击 Button 时,CheckBoxes 被选中,当 CheckBoxes 被选中并且我单击 Button 时,它未被选中。

我遇到的问题是,我只想用 XAML 完成这项工作。代码背后不是问题,但我想让它只与绑定一起工作。

所以,正如你所说:

I want to get this to work with only Bindings

您有 Window,上面只有很少的 CheckBoxButton,它会切换检查状态。设置 CheckBoxes 与一些 AllChecked 属性 的绑定(我们将在代码隐藏中创建它):

XAML:

<Window x:Class="WpfApp.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-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp"
        mc:Ignorable="d"
        Title="MainWindow" 
        Height="150" 
        Width="400"
        Name="mainWindow"
        KeyDown="OnKeyDown">
    <Window.Resources>             
        <local:BooleanToStringConverter x:Key="BoolToStringConverter"/>
    </Window.Resources>
    <Grid>
        <StackPanel x:Name="checkBoxPanel" 
                    HorizontalAlignment="Left" 
                    VerticalAlignment="Top"
                    Margin="10,10,0,0">
            <!-- Binding CheckBoxes and disabling them -->
            <CheckBox IsChecked="{Binding ElementName=mainWindow,
                                          Path=AllChecked,
                                          UpdateSourceTrigger=PropertyChanged}" 
                      Content="CheckBox1" 
                      IsEnabled="False"/>
            <CheckBox IsChecked="{Binding ElementName=mainWindow, 
                                          Path=AllChecked, 
                                          UpdateSourceTrigger=PropertyChanged}"  
                      Content="CheckBox2"
                      IsEnabled="False"/>
            <!-- Same 3 other CheckBoxes -->
        </StackPanel>
        <!-- Button also binded to same property. -->
        <!-- With Converter its Text change between "Check All" and "Uncheck All" -->
        <Button x:Name="btnCheckUncheckAll"
                Content="{Binding ElementName=mainWindow, 
                                  Path=AllChecked, 
                                  UpdateSourceTrigger=PropertyChanged, 
                                  Converter={StaticResource BoolToStringConverter},
                                  ConverterParameter=btnCheckUncheckAll}" 
                HorizontalAlignment="Center"
                VerticalAlignment="Top" 
                Margin="0,10,0,0" 
                Width="100" 
                Height="32" 
                Click="ButtonCheckUncheckAll_Click"/>
    </Grid>
</Window>

由于您的评论 “...我不想单击复选框”,示例中的所有 CheckBox 都被禁用了。正如 @Shrimperator 注意到的那样,检查一个将导致检查所有 CheckBoxes,因为它们绑定到相同的源(这是它们禁用的另一个原因)。 BooleanToStringConverter 使用 AllChecked 属性 值来设置“全部选中”或“取消全部选中”按钮文本(请参阅 code-behind 部分的代码) .我将按钮 x:Name 作为参数传递给转换器,以便将来能够将转换器用于其他不同的按钮,而不仅仅是这个按钮。

Window 看:

代码隐藏:

using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;

namespace WpfApp
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private bool allChecked;
        // Single property each CheckBox binded to
        public bool AllChecked 
        {
            get => allChecked;
            set
            {
                allChecked = value;
                // Notify binded controls that we changed value
                OnPropertyChanged(nameof(AllChecked));
            }
        }

        // INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propertyName = "") =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        // Constructor
        public MainWindow() => InitializeComponent();

        // If button control clicked - check state on each CheckBox will change
        private void ButtonCheckUncheckAll_Click(object sender, RoutedEventArgs e) =>
            SwitchCheckState();

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            // If C button pressed - check state on each CheckBox will change
            if (e.Key == Key.C)
                SwitchCheckState();
        }

        // Simply switch between True and False
        private void SwitchCheckState() =>
            AllChecked = !AllChecked;
    }

    public class BooleanToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (parameter is string buttonName && buttonName == "btnCheckUncheckAll")
                return (bool)value == true ? "Uncheck all" : "Check all";

            return string.Empty;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
            string.Empty;
    }
}

所以我们有简单的SwitchCheckState方法在TrueFalse之间改变AllChecked属性。它通过单击按钮(ButtonCheckUncheckAll_Click 处理程序)或通过 C(见鬼)按键(OnKeyDown 整个 Window 处理程序)调用。我们只改变 AllChecked 属性 值以我们希望的任何方式,当 INotifyPropertyChanged 和绑定在后面的某个地方做其他魔法时。

这是一个简化的示例,没有 ViewModels 和 DataContexting。 Post 如果您有其他问题、改进建议或需要其他解释,请发表评论。