首页 > 其他分享 >WPF Datagrid event command in mvvm via behavior

WPF Datagrid event command in mvvm via behavior

时间:2024-11-18 23:20:50浏览次数:1  
标签:via imgViewer mvvm System private Datagrid new using public

    <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>




 <Border.Background>
     <ImageBrush ImageSource="{Binding ImgSource}" Stretch="Uniform"
                 RenderOptions.BitmapScalingMode="Fant">                                            
     </ImageBrush>
 </Border.Background>

 

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

<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"
            >
            <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.IO;
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 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);
        }

        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,
                        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 class Book
    {
        public int Id { 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);
        }
    }
}






<Window x:Class="WpfApp37.ImgViewer"
        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:WpfApp37"
        mc:Ignorable="d"
        Title="ImgViewer" Height="450" Width="800">
    <Grid>
        <Grid.Background>
            <ImageBrush x:Name="img"
                        RenderOptions.BitmapScalingMode="Fant"
                        Stretch="Uniform"/>
        </Grid.Background>
    </Grid>
</Window>

 

标签:via,imgViewer,mvvm,System,private,Datagrid,new,using,public
From: https://www.cnblogs.com/Fred1987/p/18553978

相关文章

  • 【伪造检测】Noise Based Deepfake Detection via Multi-Head Relative-Interaction
    一、研究动机[!note]动机:目前基于噪声的检测是利用PhotoResponseNon-Uniformity(PRNU)实现的,这是一种由于相机感光传感器而造成的缺陷噪声,主要用图像的源识别,在伪造检测的任务中并没有很好的表现。因此在文中提出了一种基于伪造噪声痕迹的检测算法。实现原理:通过提取伪造视......
  • 详解WPF中的MVVM模式(二)
    文章目录1.视图模型优先介绍2.视图模型优先实现2.1ContentControl2.2实现代码3.视图模型优先示例4.总结继续接着上篇讲解WPF中的MVVM模式,本文主要讲解的是视图模型(ViewModelFirst)优先的实现方式。1.视图模型优先介绍在上篇文章中我们讲到,视图优先(ViewFirst)就......
  • FlashOcc_ Fast and Memory-Efficient Occupancy Prediction via Channel-to-Height P
    FlashOcc:FastandMemory-EfficientOccupancyPredictionviaChannel-to-HeightPluginZoteroAbstractGiventhecapabilityofmitigatingthelong-taildeficienciesandintricate-shapedabsenceprevalentin3Dobjectdetection,occupancypredictionhasbec......
  • UltimateDO_ An Efficient Framework to Marry Occupancy Prediction with 3D Object
    UltimateDO:AnEfficientFrameworktoMarryOccupancyPredictionwith3DObjectDetectionviaChannel2heightZoteroAbstractOccupancyand3Dobjectdetectionarecharacterizedastwostandardtasksinmodernautonomousdrivingsystem.Inordertodeploy......
  • 论文学习笔记: Generalizable Vision-Tactile Robotic Grasping Strategy forDeformabl
    文章目录目录文章目录一、摘要Abstract二、介绍 Introduction三、相关工作RelatedWork四、方法Methology4.1SensingModalities传感方式4.2TransformerModel 4.3 FactorizationofSpatial-TemporalAttention时空注意力的分解4.4TimeSformer时序变换......
  • MVVM(Model-View-ViewModel)模型
    MVVM(ModelViewViewModel)模型是一种常用于软件开发中的架构模式,尤其在前端框架(如Vue.js、React、Angular)中被广泛应用。它将程序的用户界面与业务逻辑分离,便于维护和扩展。 MVVM的三个组成部分1.Model(模型):  表示应用程序的核心数据和业务逻辑。  处理数据的获取......
  • WPF在MVVM模式下怎么实现导航功能
    在mvvm的模式下wpf通过frame实现页面跳转_哔哩哔哩_bilibili视频讲解同步可观看如下图,我们要实现点击左侧的菜单,在右侧展示不同的页面实现代码如下:一、如何从主窗体跳转到页面。1、在mainwindow.xaml的菜单栏代码里加入如下代码​ <BorderBorderBrush="#3c5254"Bord......
  • 【Winform使用DataGridView实现表格数据的添加,编辑、删除、分页功能】
    Winform使用DataGridView实现表格数据的添加,编辑、删除、分页功能。一、效果预览二、代码Form1publicpartialclassForm1:Form{privateBindingSourcebindingSource=newBindingSource();privateList<Student>students=newList<S......
  • WPF+MVVM案例实战与特效(二十六)- 3D粒子方块波浪墙效果实现
    文章目录1、案例效果2、案例实现1、文件创建2.功能代码实现3、粒子功能应用1、前端布局与样式2、代码解释2、后端功能代码1、案例效果2、案例实现1、文件创建打开Wpf_Examples项目、Models文件夹下创建3D粒子模型类ParticleCubeWaveMode......
  • WPF MVVM入门系列教程(四、数据绑定演示)
    在前面的文章中,介绍了数据绑定功能及使用方法。本文会使用一些数据绑定的实例来进行演示。演示过程中,涉及了数据模板功能,如果对数据模板功能还不熟悉,可以参考下面的链接:https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/data/data-templating-overview?view=netframeworkd......