WPF ContextMenu MenuItem Command CommandParameter Path=PlaceTarget.ItemsSource

FredGrit發表於2024-11-19
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Export" 
                              Command="{Binding ExportCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type ContextMenu}},
                        Path=PlacementTarget.ItemsSource}"/>
                    <MenuItem Header="Export Selected Items"
                              Command="{Binding ExportSelectedItemsCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type ContextMenu}},
                        Path=PlacementTarget.SelectedItems}"/>
                    <MenuItem Header="Mark As Selected"
                              Command="{Binding MarkSelectedCommand}"
           CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
     AncestorType={x:Type ContextMenu}},
     Path=PlacementTarget.SelectedItems}"/>
                    <MenuItem Header="Mark As Unselected"
      Command="{Binding MarkUnSelectedCommand}"
      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ContextMenu}},
Path=PlacementTarget.SelectedItems}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>



 public DelCommand MouseEnterCommand { get; set; }
 public DelCommand ExportCommand { get; set; }
 public DelCommand ExportSelectedItemsCommand { get; set; }
 public DelCommand MarkSelectedCommand { get; set; }
 public DelCommand MarkUnSelectedCommand { get; set; }


private void InitCommands()
{
    MouseEnterCommand = new DelCommand(MouseEnterCommandExecuted);
    ExportCommand = new DelCommand(ExportCommandExecuted);
    ExportSelectedItemsCommand = new DelCommand(ExportSelectedItemsCommandExecuted);
    MarkSelectedCommand = new DelCommand(MarkSelectedCommandExecuted);
    MarkUnSelectedCommand = new DelCommand(MarkUnSelectedCommandExecuted);
}

private void MarkUnSelectedCommandExecuted(object obj)
{
    var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
    if(items!=null && items.Any())
    {
        int itemsCount=items.Count;
        for(int i=0;i<itemsCount;i++)
        {
            items[i].IsSTEM = false;
        }
    }
}

private void MarkSelectedCommandExecuted(object obj)
{
    var items = ((System.Collections.IList)obj)?.Cast<Book>()?.ToList();
    if (items != null && items.Any())
    {
        for (int i = 0; i < items.Count(); i++)
        {
            items[i].IsSTEM = true;
        }
    }
}

private void ExportSelectedItemsCommandExecuted(object obj)
{
    var items = (System.Collections.IList)obj;
    if (items != null && items.Count > 0)
    {
        string selectedItemsStr = JsonConvert.SerializeObject(items, Formatting.Indented);
        File.WriteAllText("SelectedItems.Json", selectedItemsStr);
        MessageBox.Show("SelectedItems.Json");
    }
}

private void ExportCommandExecuted(object obj)
{
    var data = obj as ObservableCollection<Book>;
    if (data != null)
    {
        string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);
        File.AppendAllText("books.json", jsonStr);
        MessageBox.Show("Saved in books.json");
    }
}

private void MouseEnterCommandExecuted(object obj)
{
    var element = (obj as MouseEventArgs)?.OriginalSource as FrameworkElement;
    if (element != null)
    {
        var bk = element.DataContext as Book;
        if (bk != null)
        {
            ImgViewer imgViewer = new ImgViewer();
            imgViewer.img.ImageSource = bk.ImgSource;
            imgViewer.Owner = Application.Current.MainWindow;
            imgViewer.WindowState = WindowState.Maximized;
            imgViewer.ResizeMode = ResizeMode.NoResize;
            imgViewer.ShowDialog();
        }
    }
}

//xaml
<Window x:Class="WpfApp37.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:behavior="http://schemas.microsoft.com/xaml/behaviors"
        WindowState="Maximized"
        xmlns:local="clr-namespace:WpfApp37"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid
            ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
            AutoGenerateColumns="False"
            CanUserAddRows="False"
            VirtualizingPanel.IsContainerVirtualizable="True"
            VirtualizingPanel.IsVirtualizing="True"
            VirtualizingPanel.CacheLength="1"
            VirtualizingPanel.CacheLengthUnit="Item"
            SelectionMode="Extended"
            >
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Export" 
                              Command="{Binding ExportCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type ContextMenu}},
                        Path=PlacementTarget.ItemsSource}"/>
                    <MenuItem Header="Export Selected Items"
                              Command="{Binding ExportSelectedItemsCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type ContextMenu}},
                        Path=PlacementTarget.SelectedItems}"/>
                    <MenuItem Header="Mark As Selected"
                              Command="{Binding MarkSelectedCommand}"
           CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
     AncestorType={x:Type ContextMenu}},
     Path=PlacementTarget.SelectedItems}"/>
                    <MenuItem Header="Mark As Unselected"
      Command="{Binding MarkUnSelectedCommand}"
      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ContextMenu}},
Path=PlacementTarget.SelectedItems}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}" Width="200"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}" Width="200"/>
                <DataGridTemplateColumn Header="Image">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <CheckBox IsThreeState="False" Width="200"
                                          Content="IsSTEM"
                                          IsChecked="{Binding IsSTEM}"
                                          HorizontalAlignment="Stretch"
                                          VerticalAlignment="Center"/>
                                <Border Width="500"
                                        Height="200"                                        
                                        BorderThickness="3"
                                        BorderBrush="Blue">
                                    <!--<behavior:Interaction.Triggers>
                                        <behavior:EventTrigger EventName="MouseEnter">
                                            <behavior:InvokeCommandAction 
                                                Command="{Binding DataContext.MouseEnterCommand,
            RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}"
                                      PassEventArgsToCommand="True"/>
                                        </behavior:EventTrigger>
                                    </behavior:Interaction.Triggers>-->
                                    <Border.Background>
                                        <ImageBrush ImageSource="{Binding ImgSource}" Stretch="Uniform"
                                                    RenderOptions.BitmapScalingMode="Fant">
                                        </ImageBrush>
                                    </Border.Background>
                                </Border>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
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 Newtonsoft.Json;

namespace WpfApp37
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new BookVM();
            this.DataContext = vm;
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitData();
            InitCommands();
        }

        private void InitCommands()
        {
            MouseEnterCommand = new DelCommand(MouseEnterCommandExecuted);
            ExportCommand = new DelCommand(ExportCommandExecuted);
            ExportSelectedItemsCommand = new DelCommand(ExportSelectedItemsCommandExecuted);
            MarkSelectedCommand = new DelCommand(MarkSelectedCommandExecuted);
            MarkUnSelectedCommand = new DelCommand(MarkUnSelectedCommandExecuted);
        }

        private void MarkUnSelectedCommandExecuted(object obj)
        {
            var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if(items!=null && items.Any())
            {
                int itemsCount=items.Count;
                for(int i=0;i<itemsCount;i++)
                {
                    items[i].IsSTEM = false;
                }
            }
        }

        private void MarkSelectedCommandExecuted(object obj)
        {
            var items = ((System.Collections.IList)obj)?.Cast<Book>()?.ToList();
            if (items != null && items.Any())
            {
                for (int i = 0; i < items.Count(); i++)
                {
                    items[i].IsSTEM = true;
                }
            }
        }

        private void ExportSelectedItemsCommandExecuted(object obj)
        {
            var items = (System.Collections.IList)obj;
            if (items != null && items.Count > 0)
            {
                string selectedItemsStr = JsonConvert.SerializeObject(items, Formatting.Indented);
                File.WriteAllText("SelectedItems.Json", selectedItemsStr);
                MessageBox.Show("SelectedItems.Json");
            }
        }

        private void ExportCommandExecuted(object obj)
        {
            var data = obj as ObservableCollection<Book>;
            if (data != null)
            {
                string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);
                File.AppendAllText("books.json", jsonStr);
                MessageBox.Show("Saved in books.json");
            }
        }

        private void MouseEnterCommandExecuted(object obj)
        {
            var element = (obj as MouseEventArgs)?.OriginalSource as FrameworkElement;
            if (element != null)
            {
                var bk = element.DataContext as Book;
                if (bk != null)
                {
                    ImgViewer imgViewer = new ImgViewer();
                    imgViewer.img.ImageSource = bk.ImgSource;
                    imgViewer.Owner = Application.Current.MainWindow;
                    imgViewer.WindowState = WindowState.Maximized;
                    imgViewer.ResizeMode = ResizeMode.NoResize;
                    imgViewer.ShowDialog();
                }
            }
        }

        private void InitData()
        {
            var imgs = Directory.GetFiles(@"../../Images");
            if (imgs != null && imgs.Any())
            {
                int imgsCount = imgs.Count();
                BooksCollection = new ObservableCollection<Book>();
                for (int i = 0; i < 10000; i++)
                {
                    BooksCollection.Add(new Book()
                    {
                        Id = i + 1,
                        IsSTEM = (i % 5 == 0) ? true : false,
                        ISBN = $"ISBN_{i + 1}",
                        Name = $"Name_{i + 1}",
                        ImgSource = GetImgSourceViaUrl(imgs[i % imgsCount]),
                    });
                }
            }
        }

        private ImageSource GetImgSourceViaUrl(string url)
        {
            BitmapImage bmi = new BitmapImage();
            bmi.BeginInit();
            bmi.UriSource = new Uri(url, UriKind.RelativeOrAbsolute);
            bmi.EndInit();
            if (bmi.CanFreeze)
            {
                bmi.Freeze();
            }
            return bmi;
        }

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

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

        public DelCommand MouseEnterCommand { get; set; }
        public DelCommand ExportCommand { get; set; }
        public DelCommand ExportSelectedItemsCommand { get; set; }
        public DelCommand MarkSelectedCommand { get; set; }
        public DelCommand MarkUnSelectedCommand { get; set; }
    }

    public class Book
    {
        public int Id { get; set; }
        public bool IsSTEM { get; set; }
        public string Name { get; set; }
        public string ISBN { get; set; }
        public ImageSource ImgSource { 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)
        {
            if (canExecute == null)
            {
                return true;
            }
            return canExecute(parameter);
        }

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

相關文章