WPF Datagrid, add new blank row via contextmenu command not perfect but can resolve the issue concisely

private void AddRowCommandExecuted(object? obj)
{
    var dg = obj as DataGrid;
    if (dg != null)
    {
        if (dg.ItemsSource is IList list)
        {
            var itemType = list.GetType().GetGenericArguments()[0];
            var newItem = Activator.CreateInstance(itemType);

            int idx = dg.SelectedIndex;
            if (idx < 0 || idx >= list.Count)
            {
                list.Add(newItem);
            }
            else
            {
                list.Insert(idx + 1, newItem);
            }
            dg.SelectedItem = newItem;
            dg.ScrollIntoView(newItem);
        }
    }
}

 

 

 

 

 

 

image

 

 

 

 

 

 

 

 

 

image

 

 

 

<Window x:Class="WpfApp45.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:local="clr-namespace:WpfApp45"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="{Binding StatusMsg}" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="bookDg"
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  VirtualizingPanel.CacheLength="3,3"
                  ScrollViewer.CanContentScroll="True"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False">
            <DataGrid.Resources>
                <Style TargetType="DataGridRow">
                    <Setter Property="FontSize" Value="20"/>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="FontSize" Value="30"/>
                            <Setter Property="Foreground" Value="Red"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Id}"/>
                <DataGridTextColumn Binding="{Binding Name}"/>
                <DataGridTextColumn Binding="{Binding Abstract}"/>
                <DataGridTextColumn Binding="{Binding Author}"/>
                <DataGridTextColumn Binding="{Binding Content}"/>
                <DataGridTextColumn Binding="{Binding ISBN}"/>
                <DataGridTextColumn Binding="{Binding Title}"/>
                <DataGridTextColumn Binding="{Binding Topic}"/>
            </DataGrid.Columns>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Add Row"
                              Command="{Binding AddRowCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},Path=PlacementTarget}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>
    </Grid>
</Window>


//cs
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
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 WpfApp45
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM();
            this.DataContext = vm;
            this.Loaded += async (s, e) =>
            {
                await vm.InitBooksCollectionAsync();
            };
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        public MainVM()
        {
        }

        public async Task InitBooksCollectionAsync()
        {
            BooksCollection = new ObservableCollection<Book>();
            List<Book> booksList = new List<Book>();
            for (int i = 1; i < 1000001; i++)
            {
                booksList.Add(new Book()
                {
                    Id = i,
                    Name = $"Name_{i}",
                    Author = $"Author_{i}",
                    Abstract = $"Abstract_{i}",
                    Content = $"Content_{i}",
                    ISBN = $"ISBN_{i}_{Guid.NewGuid():N}",
                    Title = $"Title_{i}",
                    Topic = $"Topic_{i}"
                });

                if (i % 100000 == 0)
                {
                    await Application.Current.Dispatcher.InvokeAsync(() =>
                    {
                        var tempList = booksList.ToList();
                        booksList.Clear();
                        foreach (var bk in tempList)
                        {
                            BooksCollection.Add(bk);
                        }
                        StatusMsg = $"Loaded {BooksCollection.Count} items";
                    }, System.Windows.Threading.DispatcherPriority.Background);
                }
            }
            StatusMsg = $"{DateTime.Now} finished loading";
        }

        #region Commands
        private ICommand addRowCommand;
        public ICommand AddRowCommand
        {
            get
            {
                if (addRowCommand == null)
                {
                    addRowCommand = new DelCommand(AddRowCommandExecuted);
                }
                return addRowCommand;
            }
        }

        private void AddRowCommandExecuted(object? obj)
        {
            var dg = obj as DataGrid;
            if (dg != null)
            {
                if (dg.ItemsSource is IList list)
                {
                    var itemType = list.GetType().GetGenericArguments()[0];
                    var newItem = Activator.CreateInstance(itemType);

                    int idx = dg.SelectedIndex;
                    if (idx < 0 || idx >= list.Count)
                    {
                        list.Add(newItem);
                    }
                    else
                    {
                        list.Insert(idx + 1, newItem);
                    }
                    dg.SelectedItem = newItem;
                    dg.ScrollIntoView(newItem);
                }
            }
        }

        #endregion

        #region Props

        private string statusMsg;
        public string StatusMsg
        {
            get
            {
                return statusMsg;
            }
            set
            {
                if (value != statusMsg)
                {
                    statusMsg = value;
                    OnPropertyChanged(nameof(StatusMsg));
                }
            }
        }

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

        #endregion

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

    public class Book
    {
        public int? Id { get; set; }
        public string Name { get; set; }
        public string Abstract { get; set; }
        public string Author { get; set; }
        public string Content { get; set; }
        public string ISBN { 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)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

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

 

posted @ 2025-12-12 20:11  FredGrit  阅读(4)  评论(0)    收藏  举报