【问题标题】:How to add Checked and Unchecked events in the DataGridCheckBoxColumn?如何在 DataGridCheckBoxColumn 中添加 Checked 和 Unchecked 事件?
【发布时间】:2020-12-27 05:00:14
【问题描述】:

我正在开发一个 C# WPF 项目,我正在寻找一种将 Uncheck 和 Check 事件添加到 datagridCheckboxColumn 的技巧,我已经找到了很多解决方案,但我还没有得到我真正需要的东西。

我的目标是用灰色为每个选中的行着色,并用白色(数据网格的默认颜色)为用户的每个未选中的行着色。

选中行的事件完美运行,当我检查 datagridCheckboxColumn 时,该行被着色。

我正在寻找未选中事件的解决方案。

XAML 代码

<DataGridCheckBoxColumn Header="Choose" x:Name="choose">
                    <DataGridCheckBoxColumn.CellStyle>
                        <Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
                            <EventSetter Event="CheckBox.Checked" Handler="OnChecked"/>
                           
                        </Style>
                        
                    </DataGridCheckBoxColumn.CellStyle>
                </DataGridCheckBoxColumn>  

C# 代码


 private void OnChecked(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < datagridView.Items.Count; i++)
            {
                DataGridRow row = (DataGridRow)datagridView.ItemContainerGenerator.ContainerFromIndex(i);
                CheckBox ch = (CheckBox)datagridView.Columns[0].GetCellContent(row);
                bool ischecked = (bool)ch.IsChecked;

                if (ischecked)
                {
                    row.Background = Brushes.Gray;

                }
                
            }
        }

【问题讨论】:

    标签: c# wpf checkbox datagrid


    【解决方案1】:

    您可以使用 DataGrid.RowStyle 属性和 DataTriggers:

    XAML

    <Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
    
        <DataGrid ItemsSource="{Binding Entries}">
            <DataGrid.RowStyle>
                <Style TargetType="{x:Type DataGridRow}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsChecked}"
                                     Value="True">
                            <Setter Property="Background"
                                    Value="Gray" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>
        </DataGrid>
    </Grid>
    

    背后的代码:

    using System.Windows;
    
    namespace WpfApp1
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                DataContext = new MainViewModel();
            }
        }
    }
    

    MainViewModel:

    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    
    namespace WpfApp1
    {
        public class MainViewModel : INotifyPropertyChanged
        {
    
            public ObservableCollection<Entry> Entries
            {
                get => entries ?? (entries = new ObservableCollection<Entry>(CreateEntries()));
            }
            ObservableCollection<Entry> entries;
    
            private List<Entry> CreateEntries()
            {
                return new List<Entry>
                {
                    new Entry { Name = "Andy", IsChecked = false },
                    new Entry { Name = "Coolman", IsChecked = true },
                    new Entry { Name = "Bono", IsChecked = false }
                };
            }
    
            public void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            public event PropertyChangedEventHandler PropertyChanged;
        }
    
        public class Entry : INotifyPropertyChanged
        {
    
            public bool IsChecked
            {
                get { return isChecked; }
                set
                {
                    if (isChecked == value) return;
                    isChecked = value;
                    OnPropertyChanged();
                }
            }
            bool isChecked;
    
    
            public string Name
            {
                get { return name; }
                set
                {
                    if (name == value) return;
                    name = value;
                    OnPropertyChanged();
                }
            }
            string name;
    
            public void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            public event PropertyChangedEventHandler PropertyChanged;
        }
    }
    

    【讨论】:

    • 感谢您的回复,但我认为您的解决方案有点复杂
    • 如果你想关注 MVVM,这是我认为最简单的方法。或者,您可能希望更改 DataGrid 的行为,当失去对行的关注时,它将更新背景。这是一个解决方案:stackoverflow.com/questions/12329208/… 我认为使用您的解决方案检查/取消选中将更新所有行,而不仅仅是带有您选中/取消选中复选框的当前行。如果您愿意分享您的整个解决方案,我可以为您提供帮助。
    • 抱歉项目是私有的
    【解决方案2】:

    我找到了这个解决方案,它非常简单:

    XAML 代码:

    
    <DataGridCheckBoxColumn Header="Choose" x:Name="choose">
                        <DataGridCheckBoxColumn.CellStyle>
                            <Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
                                <EventSetter Event="CheckBox.Checked" Handler="OnChecked"/> 
                                <EventSetter Event="CheckBox.Unchecked" Handler="OnChecked"/> 
    
                               
                            </Style>
                            
                        </DataGridCheckBoxColumn.CellStyle>
                    </DataGridCheckBoxColumn>  
    

    C# 代码

    
    
     private void OnChecked(object sender, RoutedEventArgs e)
            {
                for (int i = 0; i < datagridView.Items.Count; i++)
                {
                    DataGridRow row = (DataGridRow)datagridView.ItemContainerGenerator.ContainerFromIndex(i);
                    CheckBox ch = (CheckBox)datagridView.Columns[0].GetCellContent(row);
                    bool ischecked = (bool)ch.IsChecked;
    
                    if (ischecked)
                    {
                        row.Background = Brushes.Gray;
    
                    }
                    else 
                    {
                        row.Background = Burshes.White;
                    
                }
            }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多