WPF DataGrid CheckBox Checked and Unchecked event binding to command in mvvm via behavior:InvokeCommandAction

//Key code
//xaml
<DataGridTemplateColumn Header="Select">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox x:Name="isSelectedCbx" IsThreeState="False" >
                <behavior:Interaction.Triggers>
                    <behavior:EventTrigger EventName="Checked">                                        
                        <behavior:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}},Path=DataContext.DataGridRowCheckedCmd}"
                                                      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGridRow}}"/>
                    </behavior:EventTrigger>
                    <behavior:EventTrigger EventName="Unchecked">
                        <behavior:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}},Path=DataContext.DataGridRowUnCheckedCmd}"
                                                      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGridRow}}"/>
                    </behavior:EventTrigger>
                </behavior:Interaction.Triggers>
            </CheckBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


//cs
 private void InitCmds()
 {
     ExportAllCmd = new DelCmd(ExportAllCmdExecuted);
     ExportSelectedCmd = new DelCmd(ExportSelectedCmdExecuted);
     SelectedCmd = new DelCmd(SelectedCmdExecuted);
     DataGridRowCheckedCmd = new DelCmd(DataGridRowCheckedCmdExecuted);
     DataGridRowUnCheckedCmd = new DelCmd(DataGridRowUnCheckedCmdExecuted);
 }

 private void DataGridRowUnCheckedCmdExecuted(object obj)
 {
     var row = obj as DataGridRow;
     if (row != null)
     {
         var bk = row.Item as Book;
         if (SelectedBooksCollection != null && bk != null && SelectedBooksCollection.Contains(bk))
         {
             SelectedBooksCollection.Remove(bk);
         }
     }
 }

 private void DataGridRowCheckedCmdExecuted(object obj)
 {
     var row = obj as DataGridRow;
     if (row != null)
     {
         var bk = row.Item as Book;
         if (SelectedBooksCollection != null && bk != null && !SelectedBooksCollection.Contains(bk))
         {
             SelectedBooksCollection.Add(bk);
         }
     }
 }

 

//Whole code

<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:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="DataGridRow">
            <Setter Property="FontSize" Value="20"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="FontSize" Value="30"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Export Selected" Command="{Binding ExportSelectedCmd}"
                    CommandParameter="{Binding ElementName=dg}"/>
            <Button Content="Export All"
                    Command="{Binding ExportAllCmd}"
                    CommandParameter="{Binding ElementName=dg}"/>
        </ToolBar>
        <DataGrid Grid.Row="1" x:Name="dg"
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  AutoGenerateColumns="False"  
                  SelectionMode="Extended"
                  CanUserAddRows="False"
                  SelectedItem="{Binding SelectedBook,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
            <!--<behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:InvokeCommandAction 
                        Command="{Binding SelectedCmd}" 
                        CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>-->
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Select">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox x:Name="isSelectedCbx" IsThreeState="False" >
                                <behavior:Interaction.Triggers>
                                    <behavior:EventTrigger EventName="Checked">                                        
                                        <behavior:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}},Path=DataContext.DataGridRowCheckedCmd}"
                                                                      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGridRow}}"/>
                                    </behavior:EventTrigger>
                                    <behavior:EventTrigger EventName="Unchecked">
                                        <behavior:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}},Path=DataContext.DataGridRowUnCheckedCmd}"
                                                                      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGridRow}}"/>
                                    </behavior:EventTrigger>
                                </behavior:Interaction.Triggers>
                            </CheckBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Title" Binding="{Binding Title}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using Newtonsoft.Json;
using System.IO;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new BookVM();
            this.DataContext = vm;
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitData();
            InitCmds();
        }

        private void InitCmds()
        {
            ExportAllCmd = new DelCmd(ExportAllCmdExecuted);
            ExportSelectedCmd = new DelCmd(ExportSelectedCmdExecuted);
            SelectedCmd = new DelCmd(SelectedCmdExecuted);
            DataGridRowCheckedCmd = new DelCmd(DataGridRowCheckedCmdExecuted);
            DataGridRowUnCheckedCmd = new DelCmd(DataGridRowUnCheckedCmdExecuted);
        }

        private void DataGridRowUnCheckedCmdExecuted(object obj)
        {
            var row = obj as DataGridRow;
            if (row != null)
            {
                var bk = row.Item as Book;
                if (SelectedBooksCollection != null && bk != null && SelectedBooksCollection.Contains(bk))
                {
                    SelectedBooksCollection.Remove(bk);
                }
            }
        }

        private void DataGridRowCheckedCmdExecuted(object obj)
        {
            var row = obj as DataGridRow;
            if (row != null)
            {
                var bk = row.Item as Book;
                if (SelectedBooksCollection != null && bk != null && !SelectedBooksCollection.Contains(bk))
                {
                    SelectedBooksCollection.Add(bk);
                }
            }
        }

        private void SelectedCmdExecuted(object obj)
        {
            var dg = obj as DataGrid;
            if (dg != null)
            {
                var selItems = dg.SelectedItems;
            }
        }

        private void ExportSelectedCmdExecuted(object obj)
        {
            var dg = obj as DataGrid;
            if (dg != null && SelectedBooksCollection!=null && SelectedBooksCollection.Any())
            {
                var selectedJson = JsonConvert.SerializeObject(SelectedBooksCollection, Formatting.Indented);
                WriteJsoToFile(selectedJson);
            }
        }

        private void WriteJsoToFile(string jsonStr)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "Json Files|*.json|All Files|*.*";
            if(dialog.ShowDialog()==true)
            {
                File.AppendAllText(dialog.FileName, jsonStr);
            }
        }

        private void ExportAllCmdExecuted(object obj)
        {
            var dg = obj as DataGrid;
            if (dg != null && dg.Items!=null)
            {
                string allJson = JsonConvert.SerializeObject(dg.Items, Formatting.Indented);
                WriteJsoToFile(allJson);
            }
        }

        private void InitData()
        {
            BooksCollection = new ObservableCollection<Book>();
            for (int i = 0; i < 1000000; i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = i + 1,
                    Name = $"Name_{i + 1}",
                    Title = $"Title_{i + 1}"
                });
            }
            SelectedBooksCollection = new ObservableCollection<Book>();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        public DelCmd ExportSelectedCmd { get; set; }
        public DelCmd ExportAllCmd { get; set; }
        public DelCmd SelectedCmd { get; set; }
        public DelCmd DataGridRowCheckedCmd { get; set; }
        public DelCmd DataGridRowUnCheckedCmd { get; set; }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if (value != booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }

        private Book selectedBook;
        public Book SelectedBook
        {
            get
            {
                return selectedBook;
            }
            set
            {
                if (value != selectedBook)
                {
                    selectedBook = value;
                    OnPropertyChanged(nameof(SelectedBook));
                }
            }
        }

        private ObservableCollection<Book> selectedBooksCollection;
        public ObservableCollection<Book> SelectedBooksCollection
        {
            get
            {
                return selectedBooksCollection;
            }
            set
            {
                if (value != selectedBooksCollection)
                {
                    selectedBooksCollection = value;
                    OnPropertyChanged(nameof(SelectedBooksCollection));
                }
            }
        }

    }

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
    }

    public class DelCmd : ICommand
    {
        private Action<object> execute;
        private Predicate<object> canExecute;
        public DelCmd(Action<object> executeValue, Predicate<object> canExecuteValue)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public DelCmd(Action<object> executeValue) : this(executeValue, null)
        {

        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object parameter)
        {
            if (canExecute == null)
            {
                return true;
            }
            return canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }
}

 

 

 

 

posted @ 2024-07-26 21:33  FredGrit  阅读(60)  评论(0编辑  收藏  举报