首页 > 其他分享 >WPF DataGrid Checkbox column to implement select and unselect items explicitly via behavior InvokeCo

WPF DataGrid Checkbox column to implement select and unselect items explicitly via behavior InvokeCo

时间:2024-08-06 21:38:37浏览次数:15  
标签:Checkbox CommandParameter column System SelectedBooks var using null public

<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; }
    }
}

 

标签:Checkbox,CommandParameter,column,System,SelectedBooks,var,using,null,public
From: https://www.cnblogs.com/Fred1987/p/18346042

相关文章

  • PgStatement的executeCachedSql(String sql, int flags, String @Nullable [] column
    方法代码如下:privatebooleanexecuteCachedSql(Stringsql,intflags,String@Nullable[]columnNames)throwsSQLException{//第一部分PreferQueryModepreferQueryMode=connection.getPreferQueryMode();booleanshouldUseParameterized=false;......
  • codeforces 1209E2 Rotate Columns (hard version)
    codeforces1209E2RotateColumns(hardversion)题解题目传送门:codeforcces,luogu思路状压dp,贪心。贪心对于所有列,只有列中最大值在所有列的最大值中前\(n\)大才可能对答案有贡献。证明:若有非前\(n\)大的列对某行最大值产生了贡献,则用没有被取的前\(n\)大的列代......
  • codeforces 1209E1 Rotate Columns (easy version)
    codeforces1209E1RotateColumns(easyversion)题目传送门:codeforcces,luogu思路贪心,暴力搜索贪心对于所有列,只有列中最大值在所有列的最大值中前\(n\)大才可能对答案有贡献。证明:若有非前\(n\)大的列对某行最大值产生了贡献,则用没有被取的前\(n\)大的列代替该行......
  • QTreeView 样式设置以及Checkbox复选框样式设置
    这种样式设置如下QTreeView{background:#303033;font-size:16px;color:rgba(255,255,255,1);border:0px;}QTreeView::item{background:#303033;height:40px;}QTreeView::branch{background:#303033;}QTreeView::item:hover{......
  • SAWarning: relationship X will copy column Q to column P, which conflicts with r
    在sqlalchemy之中,当一个字段对应多个relationship的时候。因为ORM要处理flush操作,而两个relationship可能都涉及到flush,以至于ORM无法同时兼顾。这时,sqlalchemy就会发出一个SAWarning。为了避免该类事件,可以通过以下配置来实现。假设,存在Parent和Child两个表,其中Child.parent_id......
  • 用navicat导入数据时,报错: [Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:0
    原因这是因为当前的MySQL(作者是5.7.23)不支持datetime为0的情况。解决方法1:修改sql_modesql_mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。查看全局sql_mode:select@@global.sql_mode;可以看到,O_ZERO_DATE、NO_ZERO_I......
  • Python - Pandas - loc vs iloc (DataFrame.loc[:,['column_name':]])
    原文链接:https://blog.csdn.net/weixin_48964486/article/details/123150832————————————————————————————————————————————————关于python数据分析常用库pandas中的DataFrame的loc和iloc取数据基本方法总结归纳及示例如下:1.......
  • uni-app的checkbox组件有些情况下视图层不更新解决方案
    应用场景问题:在使用uniapp的复选框组件checkbox实现列表的全选跟不全选功能时发现,列表的checkbox视图层在某些情况下不生效    解决方法 解决方案1:利用  this.$set改变数据,即 this.$set(item,'checked',false),这个时候视图层跟数据都一起更新了,但是在上面那种......
  • codeforces 1980 E. Permutation of Rows and Columns
    题目链接https://codeforces.com/problemset/problem/1980/E题意共输入\(T\)组测试用例,每组测试用例第一行输入两个整数\(n,m\),分别代表输入的数据的行数和列数,其中\(n*m\leq2*10^5\)。接下来输入两个\(n\)行\(m\)列的矩阵\(a,b\),对于每个矩阵中的元素\(x_{i,j}\)都是......
  • WPF generate rows and columns via C# dynamically
    //xaml<Windowx:Class="WpfApp214.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......