首页 > 其他分享 >WPF DataGridTemplateColumn.CellTemplate Command CommandParameter

WPF DataGridTemplateColumn.CellTemplate Command CommandParameter

时间:2024-09-09 21:35:20浏览次数:11  
标签:set CommandParameter get System private Command using WPF public

<DataGridTemplateColumn Header="Image" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button 
                Command="{Binding DataContext.EnterCmd,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                CommandParameter="{Binding Path=SelectedItem,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}" >
                <Image Source="{Binding ImgUrl}" Width="20" Height="50"/>
            </Button> 
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


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);
        }
    }
}

 

 

 

 

 

//xaml
<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>
                            <Button 
                                Command="{Binding DataContext.EnterCmd,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                                CommandParameter="{Binding Path=SelectedItem,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}" >
                                <Image Source="{Binding ImgUrl}" Width="20" Height="50"/>
                            </Button> 
                        </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);
        }
    }
}

 

标签:set,CommandParameter,get,System,private,Command,using,WPF,public
From: https://www.cnblogs.com/Fred1987/p/18405406

相关文章

  • python3 ModuleNotFoundError: No module named 'CommandNotFound'
    前言python3报错:ModuleNotFoundError:Nomodulenamed'CommandNotFound'这是linux安装多版本python时的一个遗留问题,如果修改了默认系统的/usr/bin/python的软连接到新安装的版本,然后在/usr/bin下将名为python3的软链接指向了新版本的python。因为Python版......
  • 不可不知的WPF几何图形(Geometry)
    在软件行业,经常会听到一句话“文不如表,表不如图”说明了图形在软件应用中的重要性。同样在WPF开发中,为了程序美观或者业务需要,经常会用到各种个样的图形。今天以一些简单的小例子,简述WPF开发中几何图形(Geometry)相关内容,仅供学习分享使用,如有不足之处,还请指正。 什么是几何图形(G......
  • python 错误提示 DeprecationWarning: find_element_by_* commands are deprecated. P
    DeprecationWarning:find_element_by_*commandsaredeprecated.Pleaseusefind_element()insteadfromselenium.webdriver.common.byimportBydriver=webdriver.Chrome("chromedriver.exe")#driver.find_element_by_name("NAME")driver.find_......
  • WPF Generic eventhandler for various event
    publicMainWindow(){InitializeComponent();this.AddHandler(ListBox.SelectionChangedEvent,newSelectionChangedEventHandler(GenericHandler));this.AddHandler(Button.ClickEvent,newRoutedEventHandler(GenericHandler));}......
  • .NET 8 + WPF 企业级工作流系统
    合集-.NET开源工具(11) 1..NET开源快捷的数据库文档查询和生成工具07-312..NET结果与错误处理利器FluentResults08-013..NET+WPF桌面快速启动工具GeekDesk08-194.Gradio.NET支持.NET8简化Web应用开发08-265..NET开源实时监控系统-WatchDog08-276.实用接地......
  • WPF ListBox ListBoxItem Selected background style
    <Windowx:Class="WpfApp340.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • 【转】[C#][WPF] 旋转的播放按钮
    转自:http://www.dmskin.com运行后播放按钮就会一直旋转,而暂停按钮不动。<Windowx:Class="WPF.Views.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quo......
  • .NET 8 + WPF 企业级工作流系统
    前言推荐一款基于.NET8、WPF、Prism.DryIoc、MVVM设计模式、Blazor以及MySQL数据库构建的企业级工作流系统的WPF客户端框架-AIStudio.Wpf.AClient6.0。项目介绍框架采用了Prism框架来实现MVVM模式,不仅简化了MVVM的典型应用场景,还充分利用了依赖注入(DI)、消息传递以及容......
  • DevExpress WPF中文教程:如何解决排序、过滤遇到的常见问题?(一)
    DevExpressWPF拥有120+个控件和库,将帮助您交付满足甚至超出企业需求的高性能业务应用程序。通过DevExpressWPF能创建有着强大互动功能的XAML基础应用程序,这些应用程序专注于当代客户的需求和构建未来新一代支持触摸的解决方案。无论是Office办公软件的衍伸产品,还是以数据为中心......
  • 搜索组件优化 - Command ⌘K
    前言:DevNow项目中我们使用了DocSearch来实现搜索功能,但是由于有以下的限制:您的网站必须是技术文档或技术博客。您必须是网站的所有者,或者至少具有更新其内容的权限您的网站必须公开可用您的网站必须已准备好生产环境。由于这些条件的限制,DocSearch只适合用在开源的技......