<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