WPF MVVM Datagrid Selected Multiple items via behavior interaction.trigger,eventname method name ,implemented the SelectionChanged in MVVM

1.Install Microsoft.Xaml.Behaviors.Wpf from Nuget;

2.Add behavior reference in xaml

xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"

3.Pass method to mvvm via behavior,interaction,trigger,eventname,TargetObject,MethodName in xaml

 <DataGrid x:Name="dg" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
               AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
               VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.IsVirtualizing="True"
               EnableColumnVirtualization="True" EnableRowVirtualization="True" 
               VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingPanel.VirtualizationMode="Recycling"
               SelectionMode="Extended">
     <behavior:Interaction.Triggers>
         <behavior:EventTrigger EventName="SelectionChanged" SourceObject="{Binding ElementName=dg}">
             <behavior:CallMethodAction TargetObject="{Binding}" MethodName="OnSelectionChanged"/>
         </behavior:EventTrigger>
     </behavior:Interaction.Triggers>
     <DataGrid.Columns>
</DataGrid>

 

4.Implmented the specified method name "OnSelectionChanged" in mvvm with the same function signature and public accessor

 

public void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var dg = sender as DataGrid;
if(dg!=null && dg.SelectedItems!=null &&dg.SelectedItems.Count>0)
{
List<Book> selectedBooks=dg.SelectedItems.Cast<Book>().ToList();
string selectedJson = JsonConvert.SerializeObject(selectedBooks,Formatting.Indented);
string filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "selectedJson.json");
System.IO.File.WriteAllText(filePath, selectedJson);
System.Diagnostics.Process.Start("notepad.exe", filePath);
}
}

 

 

The whole code

<Window x:Class="WpfApp74.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:WpfApp74" 
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <DataGrid x:Name="dg" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
                      AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                      VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.IsVirtualizing="True"
                      EnableColumnVirtualization="True" EnableRowVirtualization="True" 
                      VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingPanel.VirtualizationMode="Recycling"
                      SelectionMode="Extended">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged" SourceObject="{Binding ElementName=dg}">
                    <behavior:CallMethodAction TargetObject="{Binding}" MethodName="OnSelectionChanged"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <DataGrid.Columns>
                 <DataGridTextColumn Header="Id" Binding="{Binding Id,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                        IsReadOnly="True" Width="Auto"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Header="Title" Binding="{Binding Title,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Header="Topic" Binding="{Binding Topic,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Header="Summary" Binding="{Binding Summary,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</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 Newtonsoft.Json;

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

    //Microsoft.Xaml.Behaviors.Wpf
    public class ViewModel : INotifyPropertyChanged
    {
        public ViewModel()
        {
            InitLV();
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if (value != booksCollection)
                {
                    booksCollection = value;
                }
            }
        }
        private void InitLV()
        {
            BooksCollection = new ObservableCollection<Book>();
            for (int i = 0; i < 1000; i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = i + 1,
                    ISBN = $"ISBN_{i + 1}",
                    Name = $"Name_{i + 1}",
                    Summary = $"Summary{i + 1}",
                    Title = $"Title_{i + 1}",
                    Topic = $"Topic{i + 1}",
                });
            }
        }

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

        public void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dg = sender as DataGrid;
            if(dg!=null && dg.SelectedItems!=null &&dg.SelectedItems.Count>0)
            {
                List<Book> selectedBooks=dg.SelectedItems.Cast<Book>().ToList();
                string selectedJson = JsonConvert.SerializeObject(selectedBooks,Formatting.Indented);
                string filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "selectedJson.json");
                System.IO.File.WriteAllText(filePath, selectedJson);
                System.Diagnostics.Process.Start("notepad.exe", filePath);
            }
        }
    }

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

 

 

 

 

posted @ 2024-04-30 13:56  FredGrit  阅读(16)  评论(0编辑  收藏  举报