WPF DataGrid Checkbox column to implement select and unselect items explicitly via behavior InvokeCommandAction Command and CommandParameter

复制代码
<DataGridTemplateColumn Header="Select">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox IsThreeState="False">
                <behavior:Interaction.Triggers>
                    <behavior:EventTrigger EventName="Checked">
                        <behavior:InvokeCommandAction 
                            Command="{Binding DataContext.CheckedCmd,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"
                            CommandParameter="{Binding ElementName=dg}"
                            PassEventArgsToCommand="True" />
                    </behavior:EventTrigger>
                    <behavior:EventTrigger EventName="Unchecked">
                        <behavior:InvokeCommandAction
                            Command="{Binding DataContext.UncheckedCmd,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"
                            CommandParameter="{Binding ElementName=dg}"/>
                    </behavior:EventTrigger>
                </behavior:Interaction.Triggers>
            </CheckBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


复制代码

 

复制代码
//cs
public DelCmd CheckedCmd { get; set; } public DelCmd UncheckedCmd { get; set; } private void CheckedCmdExecuted(object obj) { var dataGrid = obj as DataGrid; if (dataGrid != null && SelectedBooks != null) { var selectedBk = dataGrid.SelectedItem as Book; if (selectedBk != null && !SelectedBooks.Contains(selectedBk)) { SelectedBooks.Add(selectedBk); } } } private void UncheckedCmdExecuted(object obj) { var dataGrid = obj as DataGrid; if (dataGrid != null && SelectedBooks != null) { var selectedBk = dataGrid.SelectedItem as Book; if (selectedBk != null && SelectedBooks.Contains(selectedBk)) { SelectedBooks.Remove(selectedBk); } } }
复制代码

 

 

 

 

复制代码
//Whole code
//xaml
<Window x:Class="WpfApp232.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:WpfApp232"
        mc:Ignorable="d" WindowState="Maximized" 
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Export All" Width="200" Command="{Binding ExportAllCmd}" 
                    CommandParameter="{Binding ElementName=dg}"/>
            <Button Content="Export Selected" Width="200" Command="{Binding ExportSelectedCmd}"/>
        </ToolBar>
        <DataGrid x:Name="dg" Grid.Row="1" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                   AutoGenerateColumns="False" SelectionMode="Extended" CanUserAddRows="False">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:InvokeCommandAction Command="{Binding SelectionChangedCmd}"
                                                  CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}" />
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Select">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsThreeState="False">
                                <behavior:Interaction.Triggers>
                                    <behavior:EventTrigger EventName="Checked">
                                        <behavior:InvokeCommandAction 
                                            Command="{Binding DataContext.CheckedCmd,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"
                                            CommandParameter="{Binding ElementName=dg}"
                                            PassEventArgsToCommand="True" />
                                    </behavior:EventTrigger>
                                    <behavior:EventTrigger EventName="Unchecked">
                                        <behavior:InvokeCommandAction
                                            Command="{Binding DataContext.UncheckedCmd,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"
                                            CommandParameter="{Binding ElementName=dg}"/>
                                    </behavior:EventTrigger>
                                </behavior:Interaction.Triggers>
                            </CheckBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>                
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTemplateColumn Header="Image">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding ImgUrl}" Width="20" Height="50"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


//cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.Eventing.Reader;
using System.IO;
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 Newtonsoft.Json;

namespace WpfApp232
{
    /// <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()
        {
            SelectionChangedCmd = new DelCmd(SelectionChangedCmdExecuted);
            CheckedCmd = new DelCmd(CheckedCmdExecuted);            
            UncheckedCmd = new DelCmd(UncheckedCmdExecuted);
            ExportAllCmd = new DelCmd(ExportAllCmdExecuted);
            ExportSelectedCmd = new DelCmd(ExportSelectedCmdExecuted);
        }

        private void ExportSelectedCmdExecuted(object obj)
        {
            if(SelectedBooks!=null && SelectedBooks.Any())
            {
                var selectedJson = JsonConvert.SerializeObject(SelectedBooks, Formatting.Indented);
                if(!string.IsNullOrWhiteSpace(selectedJson))
                {
                    WriteContenToFile("", selectedJson);
                }
            }
        }

        private void ExportAllCmdExecuted(object obj)
        {
            var daGrid = obj as DataGrid;
            if (daGrid != null && daGrid.Items != null && daGrid.Items.Count > 0)
            {
                var books = daGrid.Items.Cast<Book>().ToList();
                if (books != null && books.Any())
                {
                    string jsonStr = JsonConvert.SerializeObject(books, Formatting.Indented);
                    if(!string.IsNullOrWhiteSpace(jsonStr))
                    {
                        WriteContenToFile("", jsonStr);
                    }
                }
            }
        }

        private void WriteContenToFile(string fileName, string jsonStr)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}.json";
            }
            using (StreamWriter writer = new StreamWriter(fileName, false))
            {
                writer.WriteLine(jsonStr);
            }
            MessageBox.Show($"Saved in file :{fileName}");
        }

        private void CheckedCmdExecuted(object obj)
        {
            var dataGrid = obj as DataGrid;
            if (dataGrid != null && SelectedBooks != null)
            {
                var selectedBk = dataGrid.SelectedItem as Book;
                if (selectedBk != null && !SelectedBooks.Contains(selectedBk))
                {
                    SelectedBooks.Add(selectedBk);
                }
            }
        }

        private void UncheckedCmdExecuted(object obj)
        {
            var dataGrid = obj as DataGrid;
            if (dataGrid != null && SelectedBooks != null)
            {
                var selectedBk = dataGrid.SelectedItem as Book;
                if (selectedBk != null && SelectedBooks.Contains(selectedBk))
                {
                    SelectedBooks.Remove(selectedBk);
                }
            }
        }

        private void SelectionChangedCmdExecuted(object obj)
        {
            var daGrid= obj as DataGrid;
            if(daGrid!=null && daGrid.SelectedItems!=null && daGrid.SelectedItems.Count>0)
            {
                var books= daGrid.SelectedItems.Cast<Book>().ToList();
            }
        }

       

        private void RetrieveDataGridSelectdItems(object obj)
        {

        }

        private void InitData()
        {
            BooksCollection = new ObservableCollection<Book>();
            var imgsList = System.IO.Directory.GetFiles(@"../../Images");
            int imgLen = imgsList.Count();
            for (int i = 0; i < 10000; i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = i + 1,
                    Name = $"Name_{i + 1}",
                    ImgUrl = imgsList[i%imgLen]
                });
            }
            SelectedBooks = new ObservableCollection<Book>();
        }

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

        
        public DelCmd SelectionChangedCmd { get; set; }
        public DelCmd CheckedCmd { get; set; }
        public DelCmd UncheckedCmd { get; set; }
        public DelCmd ExportAllCmd { get; set; }
        public DelCmd ExportSelectedCmd { get; set; }

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

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

    public class DelCmd : ICommand
    {
        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;
            }
        }

        private Action<object> execute;
        private Predicate<object> canExecute;
        public bool CanExecute(object parameter)
        {
            if (canExecute == null)
            {
                return true;
            }
            return canExecute(parameter);
        }

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

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ImgUrl { get; set; }
    }
}
复制代码

 

posted @   FredGrit  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2022-08-06 Vim: Warning: Output is not to a terminal to unlock the terminal
2022-08-06 Ubuntu search keyword via grep in specified file,the short cut to capture selection screen shot in Ubuntu 20.04 is Ctrl+Shift+Alt+R to start take screenshot functions
点击右上角即可分享
微信分享提示