WPF behavior selected multiple items from datagrid and passed to mvvm, implemented the same effect as Interactivity

1.Install package,Microsoft.Xaml.Behaviors.Wpf

2.Add xaml reference in xaml

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

3.

  <behavior:Interaction.Triggers>
      <behavior:EventTrigger EventName="SelectionChanged" SourceObject="{Binding ElementName=dg}">
          <behavior:InvokeCommandAction Command="{Binding SelectionMultiItemsCmd}" 
                                        CommandParameter="{Binding ElementName=dg,Path=SelectedItems}"/>
      </behavior:EventTrigger>
  </behavior:Interaction.Triggers> 

and Convert the SelectedItems as IList then as ObservableCollection

private void SelectionMultiItemsCmdExecuted(object obj)
{
    IList items = obj as IList;
    if(items!=null && items.Count>0)
    {
         int len= items.Count;
        SelectedMultiBooksCollection = new ObservableCollection<Book>();
        for(int i=0;i<len;i++)
        {
            var tempBook = items[i] as Book;
            if(tempBook!=null) 
            {
                SelectedMultiBooksCollection.Add(tempBook);
            }
        }
    }
}

 

The whole code snippet

<Window x:Class="WpfApp58.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:WpfApp58" WindowState="Maximized"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"> 
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="dg" Grid.Row="1" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
                  VerticalAlignment="Stretch" HorizontalAlignment="Stretch" BorderBrush="Blue"
                   BorderThickness="3" SelectionMode="Extended" >
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged" SourceObject="{Binding ElementName=dg}">
                    <behavior:InvokeCommandAction Command="{Binding SelectionMultiItemsCmd}" 
                                                  CommandParameter="{Binding ElementName=dg,Path=SelectedItems}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers> 
        </DataGrid>
    </Grid>
</Window>


//xaml.cs
using System;
using System.Collections.Generic;
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;

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

    
}


//mvvm.cs
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.Web;
using System.Windows;
using System.Windows.Input;

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

        private Window win;

        public MainVM(Window winValue)
        {
            win= winValue;
            win.Loaded += Win_Loaded;
        }

        public DelegateCmd SelectionMultiItemsCmd => new DelegateCmd(SelectionMultiItemsCmdExecuted);

        private void SelectionMultiItemsCmdExecuted(object obj)
        {
            IList items = obj as IList;
            if(items!=null && items.Count>0)
            {
                 int len= items.Count;
                SelectedMultiBooksCollection = new ObservableCollection<Book>();
                for(int i=0;i<len;i++)
                {
                    var tempBook = items[i] as Book;
                    if(tempBook!=null) 
                    {
                        SelectedMultiBooksCollection.Add(tempBook);
                    }
                }
            }
        }

        private void Win_Loaded(object sender, RoutedEventArgs e)
        {
            BooksCollection = new ObservableCollection<Book>();
            for(int i=0;i<1000;i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = i + 1,
                    Title = Guid.NewGuid().ToString(),
                    Name = Guid.NewGuid().ToString(),
                    Description = Guid.NewGuid().ToString(),
                    ISBN = Guid.NewGuid().ToString(),
                    Topic = Guid.NewGuid().ToString(), 
                });
            }
        }

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

        private ObservableCollection<Book> selectedMultiBooksCollection;
        public ObservableCollection<Book> SelectedMultiBooksCollection
        {
            get
            {
                return selectedMultiBooksCollection;
            }
            set
            {
                if(value!=selectedMultiBooksCollection) 
                {
                    selectedMultiBooksCollection = value;
                    OnPropertyChanged("SelectedMultiBooksCollection");
                }
            }
        }
    }

    public class DelegateCmd : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        public event EventHandler CanExecuteChanged;
        public void RaiseCanExecuteChanged() 
        {
            var handler = CanExecuteChanged;
            if(handler!=null)
            {
                handler?.Invoke(this, EventArgs.Empty); 
            }
        }

        public DelegateCmd(Action<object> executeValue,Predicate<object> canExecuteValue)
        {
            _execute = executeValue;
            _canExecute = canExecuteValue;
        }

        public DelegateCmd(Action<object> executeValue):this(executeValue,null)
        {

        }

        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 Description { get; set; } 
        public string ISBN { get; set;} 
        public string Title { get; set;} 
        public string Topic { get; set; }

    }
}

 

 

posted @ 2024-04-15 16:47  FredGrit  阅读(10)  评论(0编辑  收藏  举报