public class DatagridMultiSelectBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
}
protected override void OnDetaching()
{
base.OnDetaching();
}
public IEnumerable SelectedItems
{
get { return (IEnumerable)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedItems. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(IEnumerable),
typeof(DatagridMultiSelectBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
}
<behavior:Interaction.Behaviors>
<local:DatagridMultiSelectBehavior/>
</behavior:Interaction.Behaviors>
<behavior:Interaction.Triggers>
<behavior:EventTrigger EventName="SelectionChanged">
<behavior:InvokeCommandAction Command="{Binding SelectedCommand}"
CommandParameter="{Binding Path=SelectedItems,ElementName=dg}"/>
</behavior:EventTrigger>
</behavior:Interaction.Triggers>
<DataGrid.Columns>
private void SelectedCommandExecuted(object obj)
{
var itemsList = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
if (itemsList == null || !itemsList.Any())
{
MessageBox.Show("Nothing selected!");
return;
}
SelectedBooks = new ObservableCollection<Book>(itemsList);
}
![]()
![]()
//xaml
<Window x:Class="WpfApp51.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:WpfApp51"
WindowState="Maximized"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style x:Key="{x:Static ToolBar.ButtonStyleKey}" TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="30"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter Property="Width" Value="200"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="FontWeight" Value="ExtraBold"/>
<Setter Property="FontSize" Value="50"/>
<Setter Property="Foreground" Value="Red"/>
<Setter Property="Width" Value="550"/>
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="{x:Type GridSplitter}">
<Setter Property="Width" Value="100"/>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition/>
</Grid.RowDefinitions>
<ToolBar Grid.Row="0">
<Button Content="Load"
Command="{Binding LoadCommand}" />
<Button Content="Export Selected"
Command="{Binding ExportSelectedCommand}"
CommandParameter="{Binding SelectedItems,ElementName=dg}"/>
</ToolBar>
<DataGrid x:Name="dg"
Grid.Row="1"
ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectionMode="Extended"
VirtualizingPanel.IsContainerVirtualizable="True"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.CacheLength="1"
VirtualizingPanel.VirtualizationMode="Recycling"
CanUserAddRows="False"
AutoGenerateColumns="False"
>
<behavior:Interaction.Behaviors>
<local:DatagridMultiSelectBehavior/>
</behavior:Interaction.Behaviors>
<behavior:Interaction.Triggers>
<behavior:EventTrigger EventName="SelectionChanged">
<behavior:InvokeCommandAction Command="{Binding SelectedCommand}"
CommandParameter="{Binding Path=SelectedItems,ElementName=dg}"/>
</behavior:EventTrigger>
</behavior:Interaction.Triggers>
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" Width="200" />
<DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}" Width="300"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="200"/>
<DataGridTextColumn Header="Title" Binding="{Binding Title}" Width="200"/>
<DataGridTextColumn Header="Topic" Binding="{Binding Topic}" Width="200"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
//cs
using Microsoft.Xaml.Behaviors;
using System;
using System.Collections;
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 Newtonsoft.Json;
using Microsoft.Win32;
using System.IO;
namespace WpfApp51
{
/// <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();
InitCommands();
}
private void InitCommands()
{
ExportSelectedCommand = new DelCommand(ExportSelectedCommandExecuted);
SelectedCommand = new DelCommand(SelectedCommandExecuted);
}
private void SelectedCommandExecuted(object obj)
{
var itemsList = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
if (itemsList == null || !itemsList.Any())
{
MessageBox.Show("Nothing selected!");
return;
}
SelectedBooks = new ObservableCollection<Book>(itemsList);
}
private void ExportSelectedCommandExecuted(object obj)
{
if (SelectedBooks == null || !SelectedBooks.Any())
{
MessageBox.Show("Nothing seletced!");
return;
}
var msgResult = MessageBox.Show($"Are you sure to export selected {SelectedBooks.Count} items","Selected Items",
MessageBoxButton.YesNo,MessageBoxImage.Question,MessageBoxResult.Yes);
if(msgResult!=MessageBoxResult.Yes)
{
return;
}
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Json Files|*.json|All Files|*.*";
dialog.FileName = $"Json_{DateTime.UtcNow.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}.json";
if (dialog.ShowDialog() == true)
{
string jsonStr = JsonConvert.SerializeObject(SelectedBooks, Formatting.Indented);
File.WriteAllText(dialog.FileName, jsonStr);
}
}
private void InitData()
{
BooksCollection = new ObservableCollection<Book>();
for (int i = 0; i < 100000; i++)
{
BooksCollection.Add(new Book()
{
Id = i + 1,
ISBN = $"ISBN_{Guid.NewGuid().ToString("N")}",
Name = $"Name_{i + 1}",
Title = $"Title_{i + 1}",
Topic = $"Topic_{i + 1}"
});
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
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 DelCommand ExportSelectedCommand { get; set; }
public DelCommand SelectedCommand { get; set; }
}
public class DatagridMultiSelectBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
}
protected override void OnDetaching()
{
base.OnDetaching();
}
public IEnumerable SelectedItems
{
get { return (IEnumerable)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedItems. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(IEnumerable),
typeof(DatagridMultiSelectBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
}
public class Book
{
public int Id { get; set; }
public string ISBN { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Topic { get; set; }
}
public class DelCommand : ICommand
{
private Action<object> execute;
private Predicate<object> canExecute;
public DelCommand(Action<object> executeValue, Predicate<object> canExecuteValue = null)
{
execute = executeValue;
canExecute = canExecuteValue;
}
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);
}
}
}