WPF DataGrid Context menu binding command and commandparameter to datacontext

 <DataGrid.ContextMenu>
     <ContextMenu>
         <MenuItem Header="Save As Json"
                   Command="{Binding DataContext.SaveJsonCmd,RelativeSource={RelativeSource Mode=FindAncestor,
             AncestorType={x:Type ContextMenu}}}"
                   CommandParameter="{Binding Path=PlacementTarget.SelectedItems,
             RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}}}" />
     </ContextMenu>
 </DataGrid.ContextMenu>


public ICommand SaveJsonCmd { get; set; }

private void InitCmds()
{
    SaveJsonCmd = new DelCmd(SaveJsonCmdExecuted);
}

private void SaveJsonCmdExecuted(object? obj)
{
    var items = ((System.Collections.IList)obj).Cast<Book>();
    if(items!=null && items.Any())
    {
        string jsonFile = $"Json_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
        string jsonStr=JsonConvert.SerializeObject(items,Formatting.Indented);
        System.IO.File.WriteAllText(jsonFile, jsonStr);
        System.Diagnostics.Debug.WriteLine($"{DateTime.Now},write {items.Count()} items to {jsonFile}");
    }
}

 

 

 

 

 

<Window x:Class="WpfApp32.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:WpfApp32"
        mc:Ignorable="d"
        Title="{Binding MainTitle}"
        WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection}"
                  IsReadOnly="True"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  VirtualizingPanel.CacheLength="5,5"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  ScrollViewer.CanContentScroll="True"
                  UseLayoutRounding="True"
                  SnapsToDevicePixels="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>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Save As Json"
                              Command="{Binding DataContext.SaveJsonCmd,RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type ContextMenu}}}"
                              CommandParameter="{Binding Path=PlacementTarget.SelectedItems,
                        RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}}}" />
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>
    </Grid>
</Window>


using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Text.Json.Serialization;
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;
using static System.Net.WebRequestMethods;

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

    public class MainVM : INotifyPropertyChanged
    {
        private HttpClient client;
        private DispatcherTimer tmr;
        string requestUrl = "http://localhost:7777/BookService.svc/getbookslist?cnt=";
        public ICommand SaveJsonCmd { get; set; }
        public MainVM()
        {
            InitCmds();
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                client=new HttpClient();
                Task.Run(async () =>
                {
                    await InitBooksCollectionAsync();
                });
                InitTimer();              
            }            
        }

        private void InitCmds()
        {
            SaveJsonCmd = new DelCmd(SaveJsonCmdExecuted);
        }

        private void SaveJsonCmdExecuted(object? obj)
        {
            var items = ((System.Collections.IList)obj).Cast<Book>();
            if(items!=null && items.Any())
            {
                string jsonFile = $"Json_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
                string jsonStr=JsonConvert.SerializeObject(items,Formatting.Indented);
                System.IO.File.WriteAllText(jsonFile, jsonStr);
                System.Diagnostics.Debug.WriteLine($"{DateTime.Now},write {items.Count()} items to {jsonFile}");
            }
        }

        private void InitTimer()
        {
            tmr = new DispatcherTimer();
            tmr.Interval = TimeSpan.FromSeconds(60);
            tmr.Tick += async (s, e) =>
            {
                await InitBooksCollectionAsync();
            };           
            tmr.Start();
        }

        private async Task InitBooksCollectionAsync(int cnt=1000000)
        {
            string jsonStr = await client.GetStringAsync($"{requestUrl}{cnt}");
            if(!string.IsNullOrWhiteSpace(jsonStr))
            {
                MainTitle = $"{DateTime.Now},received response from service {requestUrl}";
                var bksList=JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                MainTitle = $"{DateTime.Now},loaded {bksList?.Count} items,{GetMem()}";

                await Application.Current.Dispatcher.InvokeAsync(() =>
                {                    
                    if (bksList != null && bksList.Any())
                    {
                        BooksCollection = new ObservableCollection<Book>(bksList);
                    }
                    MainTitle = $"{DateTime.Now},loaded {BooksCollection.Count} items,First Id:{BooksCollection.FirstOrDefault()?.Id},Last Id:{BooksCollection.LastOrDefault()?.Id}, {GetMem()}";
                },System.Windows.Threading.DispatcherPriority.Background);               
            }
        }

        private string GetMem()
        {
            return $"memory {System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024:N2} M";
        }

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

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

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

    public class DelCmd : ICommand
    {
        private Action<object?>? execute;
        private Predicate<object?>? canExecute;
        public DelCmd(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);
        }
    }


    [DataContract]
    public class Book
    {
        [DataMember]
        public long Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string ISBN { get; set; }
        [DataMember]
        public string Author { get; set; }
        [DataMember]
        public string Abstract { get; set; }
        [DataMember]
        public string Comment { get; set; }
        [DataMember]
        public string Content { get; set; }
        [DataMember]
        public string Summary { get; set; }
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public string Topic { get; set; }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

image

 

2026-05-21 13:57:00,write 892 items to Json_202605211356599821.json

 

 

 

 

 

 

image

 

 

 

 

 

image

 

posted @ 2026-05-21 14:01  FredGrit  阅读(16)  评论(0)    收藏  举报