首页 > 其他分享 >WPF ContextMenu MenuItem CommandParameter pass whole control or SelectedItem

WPF ContextMenu MenuItem CommandParameter pass whole control or SelectedItem

时间:2024-09-22 23:45:09浏览次数:7  
标签:control CommandParameter ContextMenu bytes System bk dialog using public

CommandParameter pass SelectedItem of control

 <ListBox.ContextMenu>
     <ContextMenu>
         <MenuItem Header="Save Image"
                   Command="{Binding SaveImgCommand}"
                   CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
             AncestorType={x:Type ContextMenu}},Path=PlacementTarget.SelectedItem}"/>
     </ContextMenu>
 </ListBox.ContextMenu>



private void InitCommands()
{
    SaveImgCommand = new DelCmd(SaveImgCommandExecuted);
}

private void SaveImgCommandExecuted(object obj)
{
    var bk = obj as Book;
    if(bk!=null)
    {
        SaveFileDialog dialog = new SaveFileDialog();
        dialog.Filter = "Jpg Files|*.jpg|All Files|*.*";
        dialog.FileName= bk.Name;
        if(dialog.ShowDialog()==true)
        {
            using (FileStream fs = new FileStream(dialog.FileName,FileMode.OpenOrCreate,FileAccess.ReadWrite))
            {
                var bytes = File.ReadAllBytes(bk.ImgUrl);
                fs.Write(bytes, 0, bytes.Count());
            }
        }
    }
}


 

 

 

 

 

 

2.ContextMenu CommandParameter pass whole control

  <ListBox.ContextMenu>
      <ContextMenu>
          <MenuItem Header="Save Image"
                    Command="{Binding SaveImgCommand}"
                    CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
              AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/>                    
      </ContextMenu>
  </ListBox.ContextMenu>

  private void SaveImgCommandExecuted(object obj)
  {
      var lbx = obj as ListBox;
      if(lbx!=null && lbx.SelectedItem!=null)
      {
          var bk = lbx.SelectedItem as Book;
          if (bk != null)
          {
              SaveFileDialog dialog = new SaveFileDialog();
              dialog.Filter = "Jpg Files|*.jpg|All Files|*.*";
              dialog.FileName = bk.Name;
              if (dialog.ShowDialog() == true)
              {
                  using (FileStream fs = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                  {
                      var bytes = File.ReadAllBytes(bk.ImgUrl);
                      fs.Write(bytes, 0, bytes.Count());
                  }
              }
          }
      }
}

 

 

//Whole code
//xaml
<Window x:Class="WpfApp400.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:WpfApp400"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:BooksData x:Key="booksData"/>
    </Window.Resources>
    <Window.DataContext>
        <local:BookVM/>
    </Window.DataContext>
    <Grid>
        <ListBox ItemsSource="{StaticResource booksData}"
                 CacheMode="BitmapCache"
                 SelectedIndex="0"
            VirtualizingPanel.IsContainerVirtualizable="True"
            VirtualizingPanel.IsVirtualizing="True"
            VirtualizingPanel.VirtualizationMode="Recycling"
            VirtualizingPanel.CacheLength="100"
            VirtualizingPanel.CacheLengthUnit="Item">
            <ListBox.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Save Image"
                              Command="{Binding SaveImgCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/>                    
                </ContextMenu>
            </ListBox.ContextMenu>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding Name}"/>
                        <Image Grid.Column="1"
                               Source="{Binding ImgUrl}"
                               RenderOptions.BitmapScalingMode="LowQuality"
                               Width="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
                               Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"/>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
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 System.IO;
using Microsoft.Win32;

namespace WpfApp400
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
        }
    }


    public class BooksData : ObservableCollection<Book>
    {
        public BooksData()
        {
            var imgsList = Directory.GetFiles(@"../../Images");
            if (imgsList != null && imgsList.Any())
            {
                int imgsCount = imgsList.Count();
                for (int i = 0; i < 1000000; i++)
                {
                    this.Add(new Book()
                    {
                        Id = i + 1,
                        Name = $"Name_{i + 1}",
                        ISBN = $"ISBN_{i + 1}",
                        ImgUrl = $"{imgsList[i % imgsCount]}"
                    });
                }
            }
        }
    }

    public class BookVM
    {
        public BookVM()
        {
            InitCommands();
        }

        private void InitCommands()
        {
            SaveImgCommand = new DelCmd(SaveImgCommandExecuted);
        }

        private void SaveImgCommandExecuted(object obj)
        {
            var lbx = obj as ListBox;
            if(lbx!=null && lbx.SelectedItem!=null)
            {
                var bk = lbx.SelectedItem as Book;
                if (bk != null)
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter = "Jpg Files|*.jpg|All Files|*.*";
                    dialog.FileName = bk.Name;
                    if (dialog.ShowDialog() == true)
                    {
                        using (FileStream fs = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            var bytes = File.ReadAllBytes(bk.ImgUrl);
                            fs.Write(bytes, 0, bytes.Count());
                        }
                    }
                }
            }
            //var bk = obj as Book;
            //if(bk!=null)
            //{
            //    SaveFileDialog dialog = new SaveFileDialog();
            //    dialog.Filter = "Jpg Files|*.jpg|All Files|*.*";
            //    dialog.FileName= bk.Name;
            //    if(dialog.ShowDialog()==true)
            //    {
            //        using (FileStream fs = new FileStream(dialog.FileName,FileMode.OpenOrCreate,FileAccess.ReadWrite))
            //        {
            //            var bytes = File.ReadAllBytes(bk.ImgUrl);
            //            fs.Write(bytes, 0, bytes.Count());
            //        }
            //    }
            //}
        }

        public DelCmd SaveImgCommand { get; set; }
    }

    public class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string ISBN { get; set; }

        public string ImgUrl { get; set; }
    }

    public class DelCmd : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        private Action<object> execute;
        private Predicate<object> canExecute;
        public DelCmd(Action<object> executeValue, Predicate<object> canExecuteValue)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public DelCmd(Action<object> executeValue) : this(executeValue, null)
        {
        }

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

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

 

标签:control,CommandParameter,ContextMenu,bytes,System,bk,dialog,using,public
From: https://www.cnblogs.com/Fred1987/p/18426138

相关文章