惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Cyber Attacks, Cyber Crime and Cyber Security
N
News and Events Feed by Topic
Schneier on Security
Schneier on Security
Forbes - Security
Forbes - Security
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
www.infosecurity-magazine.com
www.infosecurity-magazine.com
A
Arctic Wolf
Google Online Security Blog
Google Online Security Blog
T
Troy Hunt's Blog
T
Tenable Blog
L
Lohrmann on Cybersecurity
C
Cisco Blogs
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
Threat Research - Cisco Blogs
Attack and Defense Labs
Attack and Defense Labs
T
The Exploit Database - CXSecurity.com
有赞技术团队
有赞技术团队
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
P
Proofpoint News Feed
雷峰网
雷峰网
Cisco Talos Blog
Cisco Talos Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cloudbric
Cloudbric
K
Kaspersky official blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
M
MIT News - Artificial intelligence
H
Heimdal Security Blog
Vercel News
Vercel News
S
SegmentFault 最新的问题
U
Unit 42
Help Net Security
Help Net Security
S
Schneier on Security
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
Microsoft Azure Blog
Microsoft Azure Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Threatpost
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Palo Alto Networks Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
宝玉的分享
宝玉的分享
Latest news
Latest news

博客园 - FredGrit

WPF ContentControl Template WPF DatagridTemplate Binding DataTemplate WPF TreeView explicitly given key name to HierarchicalDataTemplate WPF, parse XMlDocument as List WPF two separated datagrid scroll synchronously both in horizontal and vertical via behavior WPF ContentControl Template is ControlTemplate, ContentTemplate is DataTemplate and must assign value to Content explicitly WPF TreeView show WCF config file WPF itemscontrol loaded downloaded data from WCF via httpclient WPF TreeView HierarchicalDataTemplate DataTemplate, Enum get enum name WPF consume xml generated by WCF , C# deserialize xml to List WPF implemented ICommand and IDisposable WPF ContextMenu,MenuItem command can binding to datacontext's command directly WPF usercontrol pass contextmenu command via implemented Freezable class which does not attach on Visual tree, then invoked in caller MVVM WPF consume data generate by WCF and save via ContextMenu Command in MVVM C# export List<T> to excel file via EPPlus WPF ContextMenu does not rely on host visual tree, the Freezable can exist independently, convey dependency property in usercontrol to caller C# JsonConvert DeserializeObject MissingMemberHandling.Ignore when the source model is completed and the required is partial Freezable objects do not require attachment to the WPF visual tree, maintain a persistent lifetime, and serve as a reliable binding relay between a detached ContextMenu and its parent host control. C# run httplistener to act as service application asynchronously in console, semaphoreslim allow the max concurrent number WPF Microsoft.Xaml.Behaviors.WPF, EventTrigger EventName="PreviewMouseDown" the tunnel event, while the MouseDown can't trigger the command because it was swallowed WPF customize command implemented ICommand, volatile read method is thread safe, preventing cpu and comipler reorder and optimization. WPF ItemsControl load huge 50M+ data WPF consume data generated by WCF periodically in json format WPF customize command based on ICommand and manually trigger WPF consume data generated by grpc services C# produce and consume data via Google.Protobuf WCF produce message and WPF consume periodically via DispatcherTimer WCF deconstruct WebConfig includes bindings, behaviors, service, endpoint ,serviceHostingEnvironment C# insert data into SQLite in batch periodically WPF SQLite SQLiteStudio WPF customize MultiSelectComboBox based on combobox WPF DataGrid Context menu binding command and commandparameter to datacontext WCF set fixed port as http://localhost:8888/ via Project /Properties/web/project url to create virtual directory WPF Microsoft Visual Studio XAML designer is busy WCF WebHttpBinding support both http and https WCF support basicHttpBinding and webHttpBinding - FredGrit WCF TestClient set fixed configuration file WPF consume http json and update periodically via DispatcherTimer WPF Prism.Core version 9.0.537 implemented navigation register singleton with splash screen, pass global variable via RegisterSingleton method WPF render periodically via DispatcherTimer, customize behavior - FredGrit Python cosume WCF service via requests in json format WPF call webHttpBinding from WCF WCF binding webHttpBinding is used to web browser in json format both in request and response WPF invoke WCF dll periodically via DispatcherTimer WCF webHttpBinding is open for web browser and wpf WPF DataTemplateSelector WPF DataGrid customize behavior with multiple commands and command parameters then invoke in mvvm WPF DataGrid behavior customize command and command parameter then invoke and implemented in MVVM WPF ItemsControl customize behavior and save all items WCF service can be accessed by browser WPF WCF produce data as service and WPF consume data as client periodically WPF GRPC and Probuf generated data as service then consume by wpf periodically WPF customize behavior based on Microsoft.Xaml.Behaviors.Wpf with command and commandparameter WPF call data from CPP wrapper dll via CLI\CLR - FredGrit WPF customize behavior WPF get gpu information via System.Management WPF ItemsControl IsItemsHost=True WPF Customize behavior and dependency property command C# Serilog, Serilog.Sinks.Console, Serilog.Sinks.File C# Serilog both in file and console Windows powershell view huge file via command C# serialize huge data more than 100M via splitting into batch and concatenating as one big json file WPF WeakReference C# serialize datetime then deserialize, print lose precision. resolve by ToString(&quot;o&quot;) C# produce data and send via WebSocket as service, Python,Flask,HTML as consumer invoke periodically C# write generated data service and sent via websocket, then consume by python periodically C# DateTime print precision to microseconds C# WebSocket console as service provide data, another console as client,send request periodically C# WebAPI [HttpGet(&quot;{cnt}&quot;] pass argument WPF implement ICommand with async execute WPF ListBox control virtualization in mvvm WPF Data Source invoke from web api C# WebAPI
WPF customize datagrid behavior based on behavior&lt;datagrid&gt; with command and command parameter
FredGrit · 2026-05-19 · via 博客园 - FredGrit
Install-Package Microsoft.Xaml.Behaviors.Wpf
Install-Package Newtonsoft.Json
public class DatagridBehavior : Behavior<DataGrid>
{
    ContextMenu ctxMenu;
    MenuItem saveJsonMenuItem;
    MenuItem deleteMenuItem;


    public ICommand SaveJsonCommand
    {
        get { return (ICommand)GetValue(SaveJsonCommandProperty); }
        set { SetValue(SaveJsonCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SaveJsonCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SaveJsonCommandProperty =
        DependencyProperty.Register(nameof(SaveJsonCommand), typeof(ICommand),
            typeof(DatagridBehavior), new PropertyMetadata(null));





    public ICommand DeleteCommand
    {
        get { return (ICommand)GetValue(DeleteCommandProperty); }
        set { SetValue(DeleteCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for DeleteCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DeleteCommandProperty =
        DependencyProperty.Register(nameof(DeleteCommand), typeof(ICommand),
            typeof(DatagridBehavior), new PropertyMetadata(null));





    public object CmdPara
    {
        get { return (object)GetValue(CmdParaProperty); }
        set { SetValue(CmdParaProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CmdPara.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CmdParaProperty =
        DependencyProperty.Register(nameof(CmdPara), typeof(object),
            typeof(DatagridBehavior), new PropertyMetadata(null));



    public DatagridBehavior()
    {
        
    }

    protected override void OnAttached()
    {
        CreateContextMenu();
        AssociatedObject.ContextMenu = ctxMenu;
        base.OnAttached();
    }

    private void CreateContextMenu()
    {
        ctxMenu = new ContextMenu();
        saveJsonMenuItem = new MenuItem()
        {
            Header = "Save Json"
        };
        saveJsonMenuItem.Click += SaveJsonMenuItem_Click;
        ctxMenu.Items.Add(saveJsonMenuItem);

        deleteMenuItem = new MenuItem()
        {
            Header = "Delete Item"
        };
        deleteMenuItem.Click += DeleteMenuItem_Click;
        ctxMenu.Items.Add(deleteMenuItem);
    }

    private void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
    {
        DeleteCommand?.Execute(CmdPara);
    }

    private void SaveJsonMenuItem_Click(object sender, RoutedEventArgs e)
    {
        SaveJsonCommand?.Execute(CmdPara);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
    }
}

  <behavior:Interaction.Behaviors>
      <local:DatagridBehavior
    SaveJsonCommand="{Binding Path=DataContext.SaveCmd,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
    DeleteCommand="{Binding Path=DataContext.DeleteCmd,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
    CmdPara="{Binding Path=SelectedItems, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
  </behavior:Interaction.Behaviors>    




public ICommand SelectedCmd { get; set; }
public ICommand SaveCmd { get; set; }
public ICommand DeleteCmd { get; set; }

 private void InitCmds()
 {
     SelectedCmd = new DelCommand(SelectedCmdExecuted);
     SaveCmd = new DelCommand(SaveCmdExecuted);
     DeleteCmd = new DelCommand(DeleteCmdExecuted);
 }

 private void DeleteCmdExecuted(object? obj)
 {
     var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
     if(items!=null && items.Any())
     {
         foreach(var item in items)
         {
             if(BooksCollection.Remove(item))
             {
                 System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: removed {item}");
             }                    
         }
     }
 }

 private void SaveCmdExecuted(object? obj)
 {
     var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
     if(items!=null && items.Any())
     {
         string jsonStr = JsonConvert.SerializeObject(items, Formatting.Indented);
         string jsonFile = $"Json_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
         using (StreamWriter jsonWriter = new StreamWriter(jsonFile,false, Encoding.UTF8))
         {
             jsonWriter.WriteLine(jsonStr);
             System.Diagnostics.Debug.WriteLine($"{DateTime.Now},write json to {jsonFile}");
         }
     }
 }
2026-05-19 18:42:00,write json to Json_202605191842003493.json
Selected count:14,First Id:1,Last Id:14
Selected count:1,First Id:11,Last Id:11
Selected count:5,First Id:11,Last Id:15
Selected count:5,First Id:11,Last Id:15
2026-05-19 18:42:09: removed Id:11,Name:Name_11,ISBN:ISBN_11_12352a8065fd439bbd32d45fceaabbc4
2026-05-19 18:42:09: removed Id:12,Name:Name_12,ISBN:ISBN_12_e0859de5557844679935fd870e3ad33f
2026-05-19 18:42:09: removed Id:13,Name:Name_13,ISBN:ISBN_13_a21f1e5c264d43e5bda089d8ecc040ce
2026-05-19 18:42:09: removed Id:14,Name:Name_14,ISBN:ISBN_14_dd7476cee61740fba7190b022fb84cb7
2026-05-19 18:42:09: removed Id:15,Name:Name_15,ISBN:ISBN_15_3cd20b8d7e27447a8901b3e2ece17439

image

<Window x:Class="WpfApp31.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:WpfApp31"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection}"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  VirtualizingPanel.CacheLength="2,2"
                  ScrollViewer.CanContentScroll="True"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  UseLayoutRounding="True"
                  SnapsToDevicePixels="True"
                  EnableColumnVirtualization="True"
                  EnableRowVirtualization="True"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  SelectionMode="Extended"
                  IsReadOnly="True">
            <DataGrid.Resources>
                <Style TargetType="DataGridRow">
                    <Setter Property="FontSize" Value="30"/>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="FontSize" Value="50"/>
                            <Setter Property="Foreground" Value="Red"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.Resources>
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="MouseUp">
                    <behavior:InvokeCommandAction 
                        Command="{Binding SelectedCmd}"
                        PassEventArgsToCommand="True"
                        CommandParameter="{Binding Path=SelectedItems,RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}">
                    </behavior:InvokeCommandAction>
                </behavior:EventTrigger>
                <behavior:EventTrigger EventName="MouseDoubleClick">
                    <behavior:CallMethodAction
                        MethodName="DataGrid_MouseDoubleClick"
                        TargetObject="{Binding}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <behavior:Interaction.Behaviors>
                <local:DatagridBehavior
              SaveJsonCommand="{Binding Path=DataContext.SaveCmd,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
              DeleteCommand="{Binding Path=DataContext.DeleteCmd,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
              CmdPara="{Binding Path=SelectedItems, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
            </behavior:Interaction.Behaviors>            
        </DataGrid>
    </Grid>
</Window>

using Microsoft.Xaml.Behaviors;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.Eventing.Reader;
using System.IO;
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;
using System.Windows.Threading;

namespace WpfApp31
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        } 
    }

    public class MainVM : INotifyPropertyChanged
    {
        private DispatcherTimer tmr;
        private static long idx = 0;
        public ICommand SelectedCmd { get; set; }
        public ICommand SaveCmd { get; set; }
        public ICommand DeleteCmd { get; set; }
        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                Task.Run(async () =>
                {
                    await InitBooksCollectionAsync();
                });
            } 

            InitCmds(); 
        }

        private void InitCmds()
        {
            SelectedCmd = new DelCommand(SelectedCmdExecuted);
            SaveCmd = new DelCommand(SaveCmdExecuted);
            DeleteCmd = new DelCommand(DeleteCmdExecuted);
        }

        private void DeleteCmdExecuted(object? obj)
        {
            var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if(items!=null && items.Any())
            {
                foreach(var item in items)
                {
                    if(BooksCollection.Remove(item))
                    {
                        System.Diagnostics.Debug.WriteLine($"{DateTime.Now}: removed {item}");
                    }                    
                }
            }
        }

        private void SaveCmdExecuted(object? obj)
        {
            var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if(items!=null && items.Any())
            {
                string jsonStr = JsonConvert.SerializeObject(items, Formatting.Indented);
                string jsonFile = $"Json_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
                using (StreamWriter jsonWriter = new StreamWriter(jsonFile,false, Encoding.UTF8))
                {
                    jsonWriter.WriteLine(jsonStr);
                    System.Diagnostics.Debug.WriteLine($"{DateTime.Now},write json to {jsonFile}");
                }
            }
        }


        public void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var dg = sender as DataGrid;
            if (dg != null)
            {
                var items = dg.SelectedItems.Cast<Book>().ToList();
                var msg = $"Selected {items.Count} items.FirstId:{items.FirstOrDefault()?.Id},LastId:{items.LastOrDefault()?.Id}";
                System.Diagnostics.Debug.WriteLine(msg);
            }
        }

        private void SelectedCmdExecuted(object? obj)
        {
            var selectedItems = ((System.Collections.IList)obj)?.Cast<Book>();
            var msg = $"Selected count:{selectedItems.Count()},First Id:{selectedItems.FirstOrDefault()?.Id},Last Id:{selectedItems.LastOrDefault()?.Id}";
            System.Diagnostics.Debug.WriteLine(msg);
        }

        private static long GetIncrementIdx()
        {
            return Interlocked.Increment(ref idx);
        }

        private async Task InitBooksCollectionAsync(int cnt = 1000000)
        {
            BooksCollection = new ObservableCollection<Book>();
            List<Book> booksList = new List<Book>();
            for (int i = 0; i < cnt; i++)
            {
                var a = GetIncrementIdx();
                booksList.Add(new Book()
                {
                    Id = a,
                    Name = $"Name_{a}",
                    Author = $"Author_{a}",
                    Abstract = $"Abstract_{a}",
                    ISBN = $"ISBN_{a}_{Guid.NewGuid():N}",
                    Comment = $"Comment_{a}",
                    Content = $"Content_{a}",
                    Summary = $"Summary_{a}",
                    Title = $"Title_{a}",
                    Topic = $"Topic_{a}"
                });

                if (i % 100000 == 0)
                {
                    await PopulateAsync(booksList);
                }
            }

            if (booksList.Any())
            {
                await PopulateAsync(booksList);
            }
        }

        private async Task PopulateAsync(List<Book> booksList)
        {
            var tempList = booksList.ToList();
            booksList.Clear();
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                foreach (var bk in tempList)
                {
                    BooksCollection.Add(bk);
                }
                MainTitle = $"{DateTime.Now},loaded {BooksCollection.Count} items";
            }, DispatcherPriority.Background);
        }


        private IList<Book> selectedBooks;
        public IList<Book> SelectedBooks
        {
            get
            {
                return selectedBooks;
            }
            set
            {
                if (value != selectedBooks)
                {
                    selectedBooks = value;
                    OnPropertyChanged();
                }
            }
        }

        private string mainTitle = $"{DateTime.Now},loading...";
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged();
                }
            }
        }

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

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

    public class DelCommand : ICommand
    {
        private Action<object?>? execute;
        private Predicate<object?>? canExecute;
        public DelCommand(Action<object?>? executeValue, Predicate<object?>? canExecuteValue = null)
        {
            execute = executeValue ?? throw new ArgumentNullException(nameof(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?.Invoke(parameter);
        }
    }

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public string Abstract { get; set; }
        public string ISBN { 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 override string ToString()
        {
            return $"Id:{Id},Name:{Name},ISBN:{ISBN}";
        }
    }

    public class DatagridBehavior : Behavior<DataGrid>
    {
        ContextMenu ctxMenu;
        MenuItem saveJsonMenuItem;
        MenuItem deleteMenuItem;


        public ICommand SaveJsonCommand
        {
            get { return (ICommand)GetValue(SaveJsonCommandProperty); }
            set { SetValue(SaveJsonCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SaveJsonCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SaveJsonCommandProperty =
            DependencyProperty.Register(nameof(SaveJsonCommand), typeof(ICommand),
                typeof(DatagridBehavior), new PropertyMetadata(null));





        public ICommand DeleteCommand
        {
            get { return (ICommand)GetValue(DeleteCommandProperty); }
            set { SetValue(DeleteCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DeleteCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DeleteCommandProperty =
            DependencyProperty.Register(nameof(DeleteCommand), typeof(ICommand),
                typeof(DatagridBehavior), new PropertyMetadata(null));





        public object CmdPara
        {
            get { return (object)GetValue(CmdParaProperty); }
            set { SetValue(CmdParaProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CmdPara.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CmdParaProperty =
            DependencyProperty.Register(nameof(CmdPara), typeof(object),
                typeof(DatagridBehavior), new PropertyMetadata(null));



        public DatagridBehavior()
        {
            
        }

        protected override void OnAttached()
        {
            CreateContextMenu();
            AssociatedObject.ContextMenu = ctxMenu;
            base.OnAttached();
        }

        private void CreateContextMenu()
        {
            ctxMenu = new ContextMenu();
            saveJsonMenuItem = new MenuItem()
            {
                Header = "Save Json"
            };
            saveJsonMenuItem.Click += SaveJsonMenuItem_Click;
            ctxMenu.Items.Add(saveJsonMenuItem);

            deleteMenuItem = new MenuItem()
            {
                Header = "Delete Item"
            };
            deleteMenuItem.Click += DeleteMenuItem_Click;
            ctxMenu.Items.Add(deleteMenuItem);
        }

        private void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
        {
            DeleteCommand?.Execute(CmdPara);
        }

        private void SaveJsonMenuItem_Click(object sender, RoutedEventArgs e)
        {
            SaveJsonCommand?.Execute(CmdPara);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }
    }
}

image

2026-05-19 18:50:27: removed Id:392835,Name:Name_392835,ISBN:ISBN_392835_98844b65f6164770b986a011953f094f
2026-05-19 18:50:27: removed Id:392836,Name:Name_392836,ISBN:ISBN_392836_6e4ae22266c649979abae5e2f2aaa596
2026-05-19 18:50:27: removed Id:392837,Name:Name_392837,ISBN:ISBN_392837_0e577274c5704ffca4b482c1f0f19182
2026-05-19 18:50:27: removed Id:392838,Name:Name_392838,ISBN:ISBN_392838_9164c28643c44982b223c922960c6e7d
2026-05-19 18:50:27: removed Id:392839,Name:Name_392839,ISBN:ISBN_392839_b962b2fba23d44debffe3741cd349c33
2026-05-19 18:50:27: removed Id:392840,Name:Name_392840,ISBN:ISBN_392840_93ffaf1bea4a4f24a029ae8631efb465
2026-05-19 18:50:27: removed Id:392841,Name:Name_392841,ISBN:ISBN_392841_2a600c9a5f8d4f2b8dd1055039a033dc

image