WPF Behavior Interaction Triggers EventTrigger EventName CallMethodAction TargetObject MethodName

//xaml
<Window x:Class="WpfApp92.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:WpfApp92"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/> 
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="dg" Grid.Row="0" BorderBrush="Blue" BorderThickness="3" 
                  SelectionMode="Extended"  VirtualizingPanel.IsVirtualizing="True"
                  EnableRowVirtualization="True" EnableColumnVirtualization="True">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:CallMethodAction TargetObject="{Binding}" MethodName="OnSelectionChanged"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
        </DataGrid>
        <StackPanel Orientation="Horizontal" Grid.Row="1">
            <Button Content="Load Data"  BorderBrush="Blue" BorderThickness="5" HorizontalAlignment="Stretch"
                    Command="{Binding LoadCmd}" CommandParameter="{Binding ElementName=dg}" >               
            </Button>
        </StackPanel>
    </Grid>
</Window>

//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
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 WpfApp92
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM();
            this.DataContext = vm;
        } 
    }

    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 ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if(value!=booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged("BooksCollection");
                }
            }
        }
        public DelCmd LoadCmd { get; set; }
        static MainVM()
        {
        }

        public MainVM()
        {
            InitCmds();
        }
         
        private void InitCmds()
        {
            LoadCmd = new DelCmd(LoadCmdExecuted, LoadCmdCanExecute);
        }

        private bool LoadCmdCanExecute(object obj)
        {
            return true;
        }

        private void LoadCmdExecuted(object obj)
        {
            InitBooksCollection(obj);
        } 

        private void InitBooksCollection(object obj)
        {
            var booksList = new List<Book>();
            for (int i = 0; i < 10000; i++)
            {
                booksList.Add(new Book()
                {
                    Id = i + 1,
                    ISBN = $"ISBN_{i + 1}",
                    Name = $"Name_{+1}",
                    Summary = $"Summary_{i + 1}",
                    Title = $"Title_{i + 1}",
                    Topic = $"Topic_{i + 1}",
                    BookTypeEnumValue = GetBookTypeEnum(((i + 1) * 100 % 500))
                });
            }

            var dg = obj as DataGrid;
            if (dg != null)
            {
                dg.ItemsSource = booksList;
            }
        }

        private BookTypeEnum GetBookTypeEnum(int num)
        {
            BookTypeEnum bookEnum = BookTypeEnum.Science;
            switch (num)
            {
                case 100:
                    bookEnum = BookTypeEnum.Science;
                    break;
                case 200:
                    bookEnum = BookTypeEnum.Math;
                    break;
                case 300:
                    bookEnum = BookTypeEnum.Engineer;
                    break;
                case 400:
                    bookEnum = BookTypeEnum.Technology;
                    break;
                case 0:
                    bookEnum = BookTypeEnum.Computer;
                    break;
            }
            return bookEnum;
        }

        public void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dg = sender as DataGrid;
            if(dg != null) 
            {
                var selectedBooks=dg.SelectedItems;
                if (selectedBooks != null &&  selectedBooks.Count > 0)
                {
                    var selectedBooksJson = JsonConvert.SerializeObject(selectedBooks, Formatting.Indented);
                    System.IO.File.WriteAllText($"SelectedBooks{Guid.NewGuid().ToString()}_" +
                        $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json", selectedBooksJson);
                } 
            } 
        }
    }

    public enum BookTypeEnum
    {
        Science = 100,
        Math = 200,
        Engineer = 300,
        Technology = 400,
        Computer = 500
    }

    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; }
        public BookTypeEnum BookTypeEnumValue { get; set; }
    }

    public class DelCmd : 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(this, EventArgs.Empty);
            }
        }

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

        public DelCmd(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);
        }
    }
}

 

posted @ 2024-05-04 16:34  FredGrit  阅读(49)  评论(0编辑  收藏  举报