WPF datagrid keydown with customized behavior and implemented in mvvm

public class DataGridKeyDownBehavior : Behavior<DataGrid>
{
    public ICommand Command
    {
        get => (ICommand)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(DataGridKeyDownBehavior));

    protected override void OnAttached()
    {
        AssociatedObject.PreviewKeyDown+=OnKeyDown;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewKeyDown-=OnKeyDown;
    }

    private void OnKeyDown(object sender, KeyEventArgs e)
    {
        if (Command?.CanExecute(e)==true)
        {
            Command.Execute(new KeyPressEventArgs
            {
                OriginalArgs=e,
                Key=e.Key,
                DataGrid=AssociatedObject,
                SelectedItems=AssociatedObject.SelectedItems
            });
        }
    }
}

public class KeyPressEventArgs
{
    public KeyEventArgs OriginalArgs { get; set; }
    public Key Key { get; set; }
    public DataGrid DataGrid { get; set; }
    public IList SelectedItems { get; set; }
}


<behavior:Interaction.Behaviors>
    <local:DataGridKeyDownBehavior Command="{Binding BehaviorKeyDownCommand}"/>
</behavior:Interaction.Behaviors>


private ICommand behaviorKeyDownCommand;
public ICommand BehaviorKeyDownCommand
{
    get
    {
        if (behaviorKeyDownCommand==null)
        {
            behaviorKeyDownCommand=new DelCommand(BehaviorKeyDownCommandExecuted);
        }
        return behaviorKeyDownCommand;
    }
}

private void BehaviorKeyDownCommandExecuted(object? obj)
{
    var args = obj as KeyPressEventArgs;
    if (args!=null)
    {
        var selectedItemsList=args.SelectedItems.Cast<Book>().ToList();
        var pressedKey = args.Key;
    }
}

 

 

 

 

 

 

 

//all codes
//xaml
<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:IdColorConverter x:Key="idColorConverter"/>
    </Window.Resources>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False"
                  FontSize="50"                  
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.IsContainerVirtualizable="True"
                  VirtualizingPanel.CacheLength="1"
                  VirtualizingPanel.CacheLengthUnit="Item">
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="Background"
                    Value="{Binding  Id,Converter={StaticResource idColorConverter}}"/>
                </Style>
            </DataGrid.RowStyle>
            <behavior:Interaction.Behaviors>
                <local:DataGridKeyDownBehavior Command="{Binding BehaviorKeyDownCommand}"/>
            </behavior:Interaction.Behaviors>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Title" Binding="{Binding Title}"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>



//cs
using Microsoft.Xaml.Behaviors;
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO.Ports;
using System.Runtime.CompilerServices;
using System.Text;
using System.Transactions;
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 WpfApp1
{
    /// <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
    {
        int idx = 0;
        public MainVM()
        {
            InitBooks();
        }

        private void InitBooks()
        {

            List<Book> booksList = new List<Book>();
            Random rnd = new Random();
            for (int i = 0; i<10; i++)
            {
                int num = rnd.Next(1, 10);
                List<Book> partList = new List<Book>();
                for (int j = 0; j< num; j++)
                {
                    partList.Add(new Book()
                    {
                        Id=i+1,
                        Name=$"Name_{++idx}",
                        Title=$"Title_{idx}",
                        ISBN=$"{Guid.NewGuid().ToString("N")}"
                    });
                }
                booksList.AddRange(partList);
            }

            BooksCollection=new ObservableCollection<Book>(booksList);
        }

        private ICommand behaviorKeyDownCommand;
        public ICommand BehaviorKeyDownCommand
        {
            get
            {
                if (behaviorKeyDownCommand==null)
                {
                    behaviorKeyDownCommand=new DelCommand(BehaviorKeyDownCommandExecuted);
                }
                return behaviorKeyDownCommand;
            }
        }

        private void BehaviorKeyDownCommandExecuted(object? obj)
        {
            var args = obj as KeyPressEventArgs;
            if (args!=null)
            {
                var selectedItemsList=args.SelectedItems.Cast<Book>().ToList();
                var pressedKey = args.Key;
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] 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??new ObservableCollection<Book>();
            }
            set
            {
                if (value!=booksCollection)
                {
                    booksCollection=value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }

    }

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

    public class IdColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int index = (int)value;
            return index % 2 == 0 ? Brushes.Cyan : Brushes.Blue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    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)
        {
            return canExecute==null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            execute(parameter);
        }
    }

    public class DataGridKeyDownBehavior : Behavior<DataGrid>
    {
        public ICommand Command
        {
            get => (ICommand)GetValue(CommandProperty);
            set => SetValue(CommandProperty, value);
        }

        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(DataGridKeyDownBehavior));

        protected override void OnAttached()
        {
            AssociatedObject.PreviewKeyDown+=OnKeyDown;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.PreviewKeyDown-=OnKeyDown;
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (Command?.CanExecute(e)==true)
            {
                Command.Execute(new KeyPressEventArgs
                {
                    OriginalArgs=e,
                    Key=e.Key,
                    DataGrid=AssociatedObject,
                    SelectedItems=AssociatedObject.SelectedItems
                });
            }
        }
    }

    public class KeyPressEventArgs
    {
        public KeyEventArgs OriginalArgs { get; set; }
        public Key Key { get; set; }
        public DataGrid DataGrid { get; set; }
        public IList SelectedItems { get; set; }
    }
}

 

posted @ 2025-07-11 22:17  FredGrit  阅读(17)  评论(0)    收藏  举报