WPF edit DataGrid's data in ControlTemplate which acts as a ContentControl's template

Install-Package Newtonsoft.json
Install-Package Microsoft.Xaml.Behaviors.Wpf

 

<Window.Resources>
    <ControlTemplate x:Key="EditBookTemplate">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <DataGrid Grid.Row="0"
                      ItemsSource="{Binding EditBooksCollection}"
                      IsReadOnly="False"
                      AutoGenerateColumns="False"
                      CanUserAddRows="False"
                      FontSize="20">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Id" Binding="{Binding Id}" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                    <DataGridTextColumn Header="Category" Binding="{Binding Category}"/>
                    <DataGridTextColumn Header="Author" Binding="{Binding Author}"/>
                    <DataGridTextColumn Header="Comment" Binding="{Binding Comment}"/>
                    <DataGridTextColumn Header="Content" Binding="{Binding Content}"/>
                    <DataGridTextColumn Header="Summary" Binding="{Binding Summary}"/>
                    <DataGridTextColumn Header="Title" Binding="{Binding Title}"/>
                    <DataGridTextColumn Header="Topic" Binding="{Binding Topic}"/>
                    <DataGridTextColumn Header="CreateTime" Binding="{Binding CreateTime}" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>
            
            <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
                <StackPanel.Resources>
                    <Style TargetType="Button">
                        <Setter Property="FontSize" Value="30"/>
                        <Setter Property="Margin" Value="5,2"/>
                        <Setter Property="Width" Value="200"/>
                    </Style>
                </StackPanel.Resources>
                <Button Content="Save" Command="{Binding SaveCommand}"/>
                <Button Content="Cancel" Command="{Binding CancelCommand}"/>
            </StackPanel>
        </Grid>
    </ControlTemplate>
</Window.Resources>



private void EditCommandExecuted(object? obj)
{
    var editTemplate = Application.Current.MainWindow.Resources["EditBookTemplate"] as ControlTemplate;
    if(editTemplate==null)
    {
        return;
    }
    editWin = new Window();
    editWin.Title = "Edit Window";
    editWin.Owner = Application.Current.MainWindow;
    ContentControl contentCtrl = new ContentControl();
    contentCtrl.Template = editTemplate;
    editWin.Content= contentCtrl;
    editWin.DataContext = this;
    if (editWin.ShowDialog() == true)
    {
        foreach(var editBk in EditBooksCollection)
        {
            var oldBk=BksCollection.Where(x => x.Id == editBk.Id).FirstOrDefault();
            if(oldBk!=null &&!string.Equals(oldBk.ToString(),editBk.ToString()))
            {
                var idx = BksCollection.IndexOf(oldBk);
                if(idx>=0)
                {
                    editBk.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    BksCollection[idx] = editBk;
                }
            }
        }
    }
}

 

 

<Window x:Class="WpfApp12.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:WpfApp12"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="MainWindow" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Window.Resources>
        <ControlTemplate x:Key="EditBookTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <DataGrid Grid.Row="0"
                          ItemsSource="{Binding EditBooksCollection}"
                          IsReadOnly="False"
                          AutoGenerateColumns="False"
                          CanUserAddRows="False"
                          FontSize="20">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Id" Binding="{Binding Id}" IsReadOnly="True"/>
                        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                        <DataGridTextColumn Header="Category" Binding="{Binding Category}"/>
                        <DataGridTextColumn Header="Author" Binding="{Binding Author}"/>
                        <DataGridTextColumn Header="Comment" Binding="{Binding Comment}"/>
                        <DataGridTextColumn Header="Content" Binding="{Binding Content}"/>
                        <DataGridTextColumn Header="Summary" Binding="{Binding Summary}"/>
                        <DataGridTextColumn Header="Title" Binding="{Binding Title}"/>
                        <DataGridTextColumn Header="Topic" Binding="{Binding Topic}"/>
                        <DataGridTextColumn Header="CreateTime" Binding="{Binding CreateTime}" IsReadOnly="True"/>
                    </DataGrid.Columns>
                </DataGrid>
                
                <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
                    <StackPanel.Resources>
                        <Style TargetType="Button">
                            <Setter Property="FontSize" Value="30"/>
                            <Setter Property="Margin" Value="5,2"/>
                            <Setter Property="Width" Value="200"/>
                        </Style>
                    </StackPanel.Resources>
                    <Button Content="Save" Command="{Binding SaveCommand}"/>
                    <Button Content="Cancel" Command="{Binding CancelCommand}"/>
                </StackPanel>
            </Grid>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <ComboBox Grid.Row="0" ItemsSource="{Binding CategoryCollection}"
                  SelectedItem="{Binding SelectedCategory}"
                  Width="300" FontSize="30"
                  SelectedIndex="0"
                  HorizontalAlignment="Left"
                  Margin="5,2"/>

        <DataGrid Grid.Row="1" ItemsSource="{Binding BksCollection}"
                  BorderBrush="Blue"
                  BorderThickness="2"
                  IsReadOnly="True"
                  Margin="5,2"
                  SelectionMode="Extended"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="5,5"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  ScrollViewer.CanContentScroll="True"
                  HeadersVisibility="Column"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  FontSize="20">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:InvokeCommandAction Command="{Binding SelectionChangedCommand}"
                                                  PassEventArgsToCommand="True"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Edit Command"
                              Command="{Binding EditCommand}"
                              Width="300" FontSize="30"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>
    </Grid>
</Window>



using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
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 WpfApp12
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        static int cnt = 1000000;
        static List<Book> allBksList = new List<Book>(cnt);
        Window editWin;
        public MainVM()
        {

            InitData();
        }

        private void InitData()
        {
            CategoryCollection = new ObservableCollection<BookCategory>(Enum.GetValues<BookCategory>());
            
            for (int i = 1; i < cnt + 1; i++)
            {
                allBksList.Add(new Book()
                {
                    Id = i,
                    Name = $"Name_{i}",
                    Author = $"Author_{i}",
                    Category = CategoryCollection[i % 4],
                    Comment = $"Comment_{i}",
                    Content = $"Content_{i}",
                    Summary = $"Summary_{i}",
                    Title = $"Title_{i}",
                    Topic = $"Topic_{i}",
                    CreateTime = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")}",
                    UpdateTime = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")}"
                });
            }

            SelectedCategory = CategoryCollection.FirstOrDefault();
        }

        private ICommand saveCommand;
        public ICommand SaveCommand
        {
            get
            {
                if(saveCommand==null)
                {
                    saveCommand = new DelegateCommand(SaveCommandExecuted);
                }
                return saveCommand;
            }
        }

        private void SaveCommandExecuted(object? obj)
        {
            editWin?.DialogResult = true;
        }

        private ICommand cancelCommand;
        public ICommand CancelCommand
        {
            get
            {
                if(cancelCommand==null)
                {
                    cancelCommand = new DelegateCommand(CancelCommandExecuted);
                }
                return cancelCommand;
            }
        }

        private void CancelCommandExecuted(object? obj)
        {
            editWin?.DialogResult = false;
        }

        private ICommand editCommand;
        public ICommand EditCommand
        {
            get
            {
                if(editCommand==null)
                {
                    editCommand = new DelegateCommand(EditCommandExecuted);
                }
                return editCommand;
            }
        }

        private void EditCommandExecuted(object? obj)
        {
            var editTemplate = Application.Current.MainWindow.Resources["EditBookTemplate"] as ControlTemplate;
            if(editTemplate==null)
            {
                return;
            }
            editWin = new Window();
            editWin.Title = "Edit Window";
            editWin.Owner = Application.Current.MainWindow;
            ContentControl contentCtrl = new ContentControl();
            contentCtrl.Template = editTemplate;
            editWin.Content= contentCtrl;
            editWin.DataContext = this;
            if (editWin.ShowDialog() == true)
            {
                foreach(var editBk in EditBooksCollection)
                {
                    var oldBk=BksCollection.Where(x => x.Id == editBk.Id).FirstOrDefault();
                    if(oldBk!=null &&!string.Equals(oldBk.ToString(),editBk.ToString()))
                    {
                        var idx = BksCollection.IndexOf(oldBk);
                        if(idx>=0)
                        {
                            editBk.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                            BksCollection[idx] = editBk;
                        }
                    }
                }
            }
        }

        private ICommand selectionChangedCommand;
        public ICommand SelectionChangedCommand
        {
            get
            {
                if(selectionChangedCommand==null)
                {
                    selectionChangedCommand = new DelegateCommand(SelectionChangedCommandExecuted);
                }
                return selectionChangedCommand;
            }
        }

        private void SelectionChangedCommandExecuted(object? obj)
        {
            var e = obj as SelectionChangedEventArgs;
            if (e != null)
            {
                var dg = e.OriginalSource as DataGrid;
                if (dg != null)
                {
                    var selectedItems = ((System.Collections.IList)dg.SelectedItems).Cast<Book>()?.ToList();
                    SelectedBks = new ObservableCollection<Book>(selectedItems);
                    EditBooksCollection = new ObservableCollection<Book>(DeepCopy<ObservableCollection<Book>>(SelectedBks));
                }               
           }
        }

        private ObservableCollection<Book> editBooksCollection;
        public ObservableCollection<Book> EditBooksCollection
        {
            get
            {
                return editBooksCollection;
            }
            set
            {
                if(value!=editBooksCollection)
                {
                    editBooksCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private ObservableCollection<Book> selectedBks;
        public ObservableCollection<Book> SelectedBks
        {
            get
            {
                return selectedBks;
            }
            set
            {
                if(value!=selectedBks)
                {
                    selectedBks = value;
                    OnPropertyChanged();
                }
            }
        }

        private T DeepCopy<T>(T tObj)
        {
            var jsonStr = JsonConvert.SerializeObject(tObj);
            return JsonConvert.DeserializeObject<T>(jsonStr);
        }

        private BookCategory selectedCategory;
        public BookCategory SelectedCategory
        {
            get
            {
                return selectedCategory;
            }
            set
            {
                if (value != selectedCategory)
                {
                    selectedCategory = value;
                    OnPropertyChanged();
                    OnSelectedCategoryChanged();
                }
            }
        }

        private void OnSelectedCategoryChanged()
        {
            BksCollection = new ObservableCollection<Book>(allBksList.Where(x => x.Category == SelectedCategory));
        }

        private ObservableCollection<BookCategory> categoryCollection;
        public ObservableCollection<BookCategory> CategoryCollection
        {
            get
            {
                return categoryCollection;
            }
            set
            {
                if (value != categoryCollection)
                {
                    categoryCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private ObservableCollection<Book> bksCollection;
        public ObservableCollection<Book> BksCollection
        {
            get
            {
                return bksCollection;
            }
            set
            {
                if (value != bksCollection)
                {
                    bksCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = Volatile.Read(ref PropertyChanged);
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propName));
            }
        }
    }

    public class DelegateCommand : ICommand
    {
        private readonly Action<object?> execute;

        private readonly Func<object?, bool> canExecute;
        public DelegateCommand(Action<object?> executeValue, Func<object?, bool> canExecuteValue = null)
        {
            execute = executeValue ?? throw new ArgumentNullException(nameof(executeValue));
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged;
        public void RaiseCanExecuteChanged()
        {
            var handler = Volatile.Read(ref CanExecuteChanged);
            if (handler != null)
            {
                var dispatcher = Application.Current?.Dispatcher;
                if (dispatcher != null)
                {
                    if (dispatcher.CheckAccess())
                    {
                        handler(this, EventArgs.Empty);
                    }
                    else
                    {
                        dispatcher.Invoke(() =>
                        {
                            handler(this, EventArgs.Empty);
                        }, System.Windows.Threading.DispatcherPriority.Background);
                    }
                }
            }
        }

        public bool CanExecute(object? parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

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

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public BookCategory Category { get; set; }
        public string Author { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
        public string CreateTime { get; set; }
        public string UpdateTime { get; set; }

        public override string ToString()
        {
            return $"Id:{Id},Name:{Name},Category:{Enum.GetName(typeof(BookCategory), Category)},Author:{Author}," +
                $"Comment:{Comment},Content:{Content},Summary:{Summary},Title:{Title},Topic:{Topic},CreateTime:{CreateTime}," +
                $"UpdateTime:{UpdateTime}";
        }
    }

    public enum BookCategory
    {
        Science = 10,
        Technology = 20,
        Engineering = 30,
        Math = 40
    }
}

 

 

 

 

image

 

 

image

 

 

 

image

 

 

 

 

 

 

image

 

posted @ 2026-11-22 17:51  FredGrit  阅读(4)  评论(0)    收藏  举报