WPF DataGridTemplateColumn.CellTemplate Command CommandParameter

复制代码
 <DataGridTemplateColumn Header="Image" >
     <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
             <Image Source="{Binding ImgUrl}" Width="20" Height="50">
                 <behavior:Interaction.Triggers>
                     <behavior:EventTrigger EventName="MouseDown">
                         <behavior:InvokeCommandAction 
                             Command="{Binding DataContext.EnterCmd,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                             CommandParameter="{Binding Path=SelectedItem,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}">
                         </behavior:InvokeCommandAction>
                     </behavior:EventTrigger>
                 </behavior:Interaction.Triggers>
             </Image>
         </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>



    EnterCmd = new DelCmd(EnterCmdExecuted,EnterCmdCanExecute);
 

private bool EnterCmdCanExecute(object obj)
{
    return true;
} 

private void EnterCmdExecuted(object obj)
{
    var seletedItem = obj as Book;
    if (seletedItem != null)
    {
        string fullPath = System.IO.Path.GetFullPath(seletedItem.ImgUrl);
        if (System.IO.File.Exists(fullPath))
        {
            ProcessStartInfo startInfo = new ProcessStartInfo(fullPath);
            startInfo.WindowStyle = ProcessWindowStyle.Maximized;
            Process.Start(startInfo);
        }
    }
}
复制代码

 

 

 

复制代码
<Window x:Class="WpfApp349.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"
        xmlns:local="clr-namespace:WpfApp349"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Load" Command="{Binding LoadCmd}" Width="100"/>
            <Button Content="Export As Json" Command="{Binding ExportJsonCmd}" Width="100"/>
            <Button Content="Export As Excel" Command="{Binding ExportExcelCmd}" Width="100"/>
        </ToolBar>
        <DataGrid Grid.Row="1" 
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.CacheLength="100"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  VirtualizingPanel.IsContainerVirtualizable="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False"
                  BorderBrush="Black" BorderThickness="3"
                  SelectedItem="{Binding SelectedBk}">
            <!--<DataGrid.Resources>
                <Style TargetType="{x:Type DataGridCell}">
                    <EventSetter Event="MouseEnter" Handler="EventSetter_OnHandler"/>
                </Style>
            </DataGrid.Resources>-->
            <!--<behavior:Interaction.Triggers>
                --><!--<behavior:EventTrigger EventName="MouseDown">
                    <behavior:CallMethodAction MethodName="Image_MouseDown" TargetObject="{Binding}"/>
                </behavior:EventTrigger>--><!--
                <behavior:EventTrigger EventName="MouseEnter">
                    <behavior:InvokeCommandAction Command="{Binding EnterCmd}" 
                                                  CommandParameter="{Binding SelectedBk}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>-->
             
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Author" Binding="{Binding Author}"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}"/>
                <DataGridTextColumn Header="Title" Binding="{Binding Title}"/>
                <DataGridTextColumn Header="Topic" Binding="{Binding Topic}"/>
                <DataGridTemplateColumn Header="Image" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding ImgUrl}" Width="20" Height="50">
                                <behavior:Interaction.Triggers>
                                    <behavior:EventTrigger EventName="MouseDown">
                                        <behavior:InvokeCommandAction 
                                            Command="{Binding DataContext.EnterCmd,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                                            CommandParameter="{Binding Path=SelectedItem,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}">
                                        </behavior:InvokeCommandAction>
                                    </behavior:EventTrigger>
                                </behavior:Interaction.Triggers>
                            </Image>
                        </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.Diagnostics;
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;

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

        private void DataGridCell_PreviewMouseMove(object sender, MouseEventArgs e)
        {

        }

        private void Image_MouseDown(object sender, MouseButtonEventArgs e)
        {

        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        public MainVM()
        { 
            InitCommands();
        }

        private void InitCommands()
        {
            LoadCmd = new DelCmd(LoadCmdExecuted);
            ExportExcelCmd = new DelCmd(ExportExcelCmdExecuted);
            ExportJsonCmd = new DelCmd(ExportJsonCmdExecuted);
            EnterCmd = new DelCmd(EnterCmdExecuted,EnterCmdCanExecute);
        }

        private bool EnterCmdCanExecute(object obj)
        {
            return true;
        } 

        private void EnterCmdExecuted(object obj)
        {
            var seletedItem = obj as Book;
            if (seletedItem != null)
            {
                string fullPath = System.IO.Path.GetFullPath(seletedItem.ImgUrl);
                if (System.IO.File.Exists(fullPath))
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo(fullPath);
                    startInfo.WindowStyle = ProcessWindowStyle.Maximized;
                    Process.Start(startInfo);
                }
            }
        }

        public void DataGridTemplateColumn_MouseEnter(object sender, MouseEventArgs e)
        {

        }

        private void ExportExcelCmdExecuted(object obj)
        {
             
        }

        private void ExportJsonCmdExecuted(object obj)
        {
           
        }

        private void LoadCmdExecuted(object obj)
        {
            InitData();
        }

        private void InitData()
        {
            BooksCollection = new ObservableCollection<Book>();

            var imgsList = System.IO.Directory.GetFiles(@"../../Images");
            int imgsCount = imgsList.Count();
            for(int i=0;i<100000;i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id=i+1,
                    Name=$"Name_{i+1}",
                    Author=$"Author_{i+1}",
                    ISBN=$"ISBN_{i+1}",
                    Title=$"Title_{i+1}",
                    Topic=$"Topic_{i+1}",
                    ImgUrl = imgsList[i%imgsCount]
                });
            }
        }

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

        private Book selectedBk;
        public Book SelectedBk
        {
            get
            {
                return selectedBk;
            }
            set
            {
                if(value!= selectedBk)
                {
                    selectedBk = value;
                    OnPropertyChanged(nameof(SelectedBk));
                }
            }
        }

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

        public DelCmd LoadCmd { get; set; }

        public DelCmd ExportJsonCmd { get; set; }

        public DelCmd ExportExcelCmd { get; set; }

        public DelCmd EnterCmd { get; set; }
    }

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

        public string Name { get; set; }

        public string Author { get; set; }

        public string ISBN { get; set; }

        public string Title { get; set; }

        public string Topic { get; set; }       

        public string ImgUrl { get; set; }
    }

    public class DelCmd : ICommand
    {
        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 event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

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

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }
}
复制代码

 

posted @   FredGrit  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2023-09-09 MySQL
2023-09-09 Linux commands
2023-09-09 Uninstall mysql completely from ubuntu
2019-09-09 Wpf Prism.Unity 7
点击右上角即可分享
微信分享提示