WPF ItemsControl edit via ControlTemplate, DeepClone via JsonConvert SerializeObject and DeserializeObject

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

 

<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:local="clr-namespace:WpfApp1"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Window.Resources>
        <DataTemplate x:Key="BkDataTemplate" DataType="{x:Type local:Book}">
            <Border Margin="5,2" BorderBrush="Cyan" BorderThickness="1">
                <Grid>
                    <Grid.Resources>
                        <Style TargetType="TextBlock">
                            <Setter Property="FontSize" Value="30"/>
                            <Setter Property="FontWeight" Value="SemiBold"/>
                            <Setter Property="HorizontalAlignment" Value="Center"/>
                            <Setter Property="VerticalAlignment" Value="Center"/>
                        </Style>
                    </Grid.Resources>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Id}" Grid.Row="0" Grid.Column="0"/>
                    <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/>
                    <TextBlock Text="{Binding ISBN}" Grid.Row="0" Grid.Column="2"/>
                    <TextBlock Text="{Binding Author}" Grid.Row="1" Grid.Column="0"/>
                    <TextBlock Text="{Binding Comment}" Grid.Row="1" Grid.Column="1"/>
                    <TextBlock Text="{Binding Content}" Grid.Row="1" Grid.Column="2"/>
                    <TextBlock Text="{Binding Summary}" Grid.Row="2" Grid.Column="0"/>
                    <TextBlock Text="{Binding Title}" Grid.Row="2" Grid.Column="1"/>
                    <TextBlock Text="{Binding Topic}" Grid.Row="2" Grid.Column="2"/>
                    <TextBlock Text="{Binding Category}" Grid.Row="3" Grid.Column="0"/>
                    <TextBlock Text="{Binding CreateTime}" Grid.Row="3" Grid.Column="1"/>
                    <TextBlock Text="{Binding Id}" Grid.Row="3" Grid.Column="2"/>
                </Grid>
            </Border>
        </DataTemplate>

        <DataTemplate DataType="{x:Type local:Book}"
                      x:Key="EditBookDataTemplate">
            <Border BorderBrush="Blue" BorderThickness="1" Margin="5,2">
                <Grid Grid.Row="0">
                    <Grid.Resources>
                        <Style TargetType="TextBlock">
                            <Setter Property="FontSize" Value="30"/>
                            <Setter Property="FontWeight" Value="SemiBold"/>
                            <Setter Property="HorizontalAlignment" Value="Center"/>
                            <Setter Property="VerticalAlignment" Value="Center"/>
                        </Style>
                        <Style TargetType="TextBox">
                            <Setter Property="FontSize" Value="30"/>
                            <Setter Property="FontWeight" Value="SemiBold"/>
                            <Setter Property="HorizontalAlignment" Value="Stretch"/>
                            <Setter Property="HorizontalContentAlignment" Value="Center"/>
                            <Setter Property="VerticalAlignment" Value="Stretch"/>
                            <Setter Property="VerticalContentAlignment" Value="Center"/>
                        </Style>
                    </Grid.Resources>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Id}" Grid.Row="0" Grid.Column="0"/>
                    <TextBox Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/>
                    <TextBox Text="{Binding ISBN}" Grid.Row="0" Grid.Column="2"/>
                    <TextBox Text="{Binding Author}" Grid.Row="1" Grid.Column="0"/>
                    <TextBox Text="{Binding Comment}" Grid.Row="1" Grid.Column="1"/>
                    <TextBox Text="{Binding Content}" Grid.Row="1" Grid.Column="2"/>
                    <TextBox Text="{Binding Summary}" Grid.Row="2" Grid.Column="0"/>
                    <TextBox Text="{Binding Title}" Grid.Row="2" Grid.Column="1"/>
                    <TextBox Text="{Binding Topic}" Grid.Row="2" Grid.Column="2"/>
                    <TextBox Text="{Binding Category}" Grid.Row="3" Grid.Column="0"/>
                    <TextBox Text="{Binding CreateTime}" Grid.Row="3" Grid.Column="1"/>
                    <TextBox Text="{Binding Id}" Grid.Row="3" Grid.Column="2"/>
                </Grid>
            </Border>
        </DataTemplate>

        <ControlTemplate x:Key="EditControlTemplate" TargetType="ContentControl">
            <Grid Margin="5,2">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>

                <ItemsControl Grid.Row="0" ItemsSource="{Binding SelectedBksCollection}"
                              ItemTemplate="{StaticResource EditBookDataTemplate}"
                              VirtualizingPanel.IsVirtualizing="True"
                              VirtualizingPanel.VirtualizationMode="Recycling"
                              VirtualizingPanel.CacheLength="5,5"
                              VirtualizingPanel.CacheLengthUnit="Item"
                              ScrollViewer.CanContentScroll="True"
                              ScrollViewer.IsDeferredScrollingEnabled="True">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.Template>
                        <ControlTemplate>
                            <ScrollViewer CanContentScroll="True">
                                <ItemsPresenter HorizontalAlignment="Stretch"/>
                            </ScrollViewer>
                        </ControlTemplate>
                    </ItemsControl.Template>
                </ItemsControl>

                <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="150"/>
                        </Style>
                    </StackPanel.Resources>
                    <Button Content="Save" Command="{Binding SaveCommand}"/>
                    <Button Content="Cancel" Command="{Binding CancelCommand}"/>
                </StackPanel>
            </Grid>

        </ControlTemplate>

        <ControlTemplate x:Key="ItemsControlTemplate" TargetType="ContentControl">
            <ItemsControl ItemsSource="{Binding BksCollection}"
                          ItemTemplate="{StaticResource BkDataTemplate}"                         
                          VirtualizingPanel.IsVirtualizing="True"
                          VirtualizingPanel.VirtualizationMode="Recycling"
                          VirtualizingPanel.CacheLength="5,5"
                          VirtualizingPanel.CacheLengthUnit="Item"
                          ScrollViewer.CanContentScroll="True"
                          ScrollViewer.IsDeferredScrollingEnabled="True">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.Template>
                    <ControlTemplate>
                        <ScrollViewer CanContentScroll="True">
                            <ItemsPresenter HorizontalAlignment="Stretch"/>
                        </ScrollViewer>
                    </ControlTemplate>
                </ItemsControl.Template>
                <ItemsControl.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Edit Selected"
                                  Width="300"
                                  FontSize="30"
                                  Command="{Binding EditSelectedCommand}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},Path=PlacementTarget}"/>
                    </ContextMenu>
                </ItemsControl.ContextMenu>
                <behavior:Interaction.Triggers>
                    <behavior:EventTrigger EventName="SelectionChanged">
                        <behavior:InvokeCommandAction Command="{Binding SelectionChangedCommand}"
                                                      PassEventArgsToCommand="True"/>
                    </behavior:EventTrigger>
                </behavior:Interaction.Triggers>
            </ItemsControl>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource ItemsControlTemplate}"
                        Content="{Binding}"/>
    </Grid>
</Window>


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

    public class MainVM : INotifyPropertyChanged
    {
        private static BookCategory[] categoryArr = Enum.GetValues<BookCategory>();
        private static int len = categoryArr.Length;
        private static long id = 1;
        private static (long, long) GetStartEnd(int cnt = 1000000)
        {
            long end = Interlocked.Add(ref id, cnt);
            long start = end - cnt;
            return (start, end);
        }

        private PeriodicTimer tmr = new PeriodicTimer(TimeSpan.FromSeconds(10));
        private CancellationTokenSource cts = new CancellationTokenSource();

        private Window editWin;
        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = PeriodicTimerAsync();
                InitBksCollection();
            }
        }

        private async Task PeriodicTimerAsync()
        {
            while (await tmr.WaitForNextTickAsync(cts.Token))
            {
                MainTitle = $"{DateTime.Now},memory:{System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 / 1024.0 / 1024.0:F2} M";
            }
        }

        private void InitBksCollection(int cnt = 1000000)
        {
            List<Book> bksList = new List<Book>(cnt);
            var (start, end) = GetStartEnd(cnt);
            for (long i = start; i <= end; i++)
            {
                bksList.Add(new Book()
                {
                    Id = i,
                    Name = $"Name_{i}",
                    Author = $"Author_{i}",
                    Comment = $"Comment_{i}",
                    Content = $"Content_{i}",
                    ISBN = $"ISBN_{i}_{Guid.NewGuid():N}",
                    Summary = $"Summary_{i}",
                    Category = categoryArr[i % len],
                    Title = $"Title_{i}",
                    Topic = $"Topic_{i}",
                    CreateTime = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}"
                });
            }

            BksCollection = new ObservableCollection<Book>(bksList);
        }

        private ICommand editSelectedCommand;
        public ICommand EditSelectedCommand
        {
            get
            {
                if(editSelectedCommand==null)
                {
                    editSelectedCommand = new DelegateCommand(EditSelectedCommandExecuted);
                }
                return editSelectedCommand;
            }
        }

        private void EditSelectedCommandExecuted(object? obj)
        {
            var itemsCtrl = obj as ItemsControl;
            if(itemsCtrl!=null)
            {
                var items = ((System.Collections.IList)itemsCtrl.Items).Cast<Book>()?.ToList();
                var editTemplate = Application.Current.MainWindow.Resources["EditControlTemplate"] as ControlTemplate;
                if(editTemplate!=null)
                {
                    ContentControl ctrl = new ContentControl();
                    ctrl.Template = editTemplate;
                    editWin = new Window();
                    editWin.Content= ctrl;
                    SelectedBksCollection=new ObservableCollection<Book>(DeepClone<List<Book>>(items));
                    editWin.DataContext = this;
                    editWin.Title = $"Edit Window";
                    if (editWin.ShowDialog() == true)
                    {
                        BksCollection = new ObservableCollection<Book>(DeepClone<ObservableCollection<Book>>(SelectedBksCollection));
                    }
                }
            }
        }

        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 static T DeepClone<T>(T obj)
        {
            string jsonStr = JsonConvert.SerializeObject(obj);
            return JsonConvert.DeserializeObject<T>(jsonStr);
        }

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

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

        }

        private void SelectionChangedCommandExecuted(object? obj)
        {
             
        }

        private string mainTitle = $"{DateTime.Now}";
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = 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 Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string ISBN { 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 BookCategory Category { get; set; }
        public string CreateTime { get; set; }
    }

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

    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.InvokeAsync(() =>
                        {
                            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);
        }
    }
}

 

 

 

image

 

 

 

 

 

 

 

 

 

image

 

 

image

 

 

 

 

 

image

 

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