首页 > 其他分享 >WPF datagrid implement multi select via behavior selectionchanged event in MVVM

WPF datagrid implement multi select via behavior selectionchanged event in MVVM

时间:2024-11-03 15:42:34浏览次数:3  
标签:multi via MVVM get Windows System set using public

<DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
          CanUserAddRows="False"
          AutoGenerateColumns="False"
          SelectionMode="Extended">
    <behavior:Interaction.Triggers>
        <behavior:EventTrigger EventName="SelectionChanged">
            <behavior:CallMethodAction MethodName="DataGrid_SelectionChanged" 
                                       TargetObject="{Binding}"/>
        </behavior:EventTrigger>
    </behavior:Interaction.Triggers>


public void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var dg = e.OriginalSource as DataGrid;
    if(dg!=null)
    {
        var items = dg.SelectedItems?.Cast<Book>().ToList();
        if(items!=null && items.Any())
        {
            MessageBox.Show($"Selected {items.Count()}!\n");
        }
    }
}

 

 

 

 

//xaml
<Window x:Class="WpfApp26.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:WpfApp26"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:BookVM/> 
    </Window.DataContext>
    <Window.Resources>
        <local:SizeConverter x:Key="sizeConverter"/>
    </Window.Resources>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  CanUserAddRows="False"
                  AutoGenerateColumns="False"
                  SelectionMode="Extended">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:CallMethodAction MethodName="DataGrid_SelectionChanged" 
                                               TargetObject="{Binding}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}"/>
                <DataGridTemplateColumn Header="Image">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border 
                                Width="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                                Converter={StaticResource sizeConverter}}"
                                Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                                Converter={StaticResource sizeConverter}}">
                                <Border.Background>
                                    <ImageBrush ImageSource="{Binding ImgSource}" Stretch="Uniform" />
                                </Border.Background>
                            </Border>
                        </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.Linq;
using System.Security.Policy;
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 System.Data.SqlTypes;
using System.Globalization;

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

    public class BookVM: INotifyPropertyChanged
    {
        private List<string> imgsList { get; set; }
        private int imgsCount = 0;

        public BookVM()
        {
            InitData();
        }

        private void InitData()
        {
            var imgs = Directory.GetFiles(@"../../Images");
            if (imgs != null && imgs.Any())
            {
                imgsCount = imgs.Count();
                imgsList = new List<string>(imgs);
                BooksCollection = new ObservableCollection<Book>();
                for(int i=0;i<10000;i++)
                {
                    Book book = new Book()
                    {
                        Id=i+1,
                        ISBN=$"ISBN_{i+1}",
                        Name=$"Name_{i+1}",
                        Topic=$"Topic_{i+1}",
                        ImgUrl = $"{imgs[i%imgsCount]}",
                        ImgSource=GetImgSource(imgs[i%imgsCount])
                    };
                    BooksCollection.Add(book);
                }
            }
        }

        private ImageSource GetImgSource(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 void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dg = e.OriginalSource as DataGrid;
            if(dg!=null)
            {
                var items = dg.SelectedItems?.Cast<Book>().ToList();
                if(items!=null && items.Any())
                {
                    MessageBox.Show($"Selected {items.Count()}!\n");
                }
            }
        }

        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
            {
                if (booksCollection==null)
                {
                    booksCollection = new ObservableCollection<Book>();
                }
                return booksCollection;
            }
            set
            {
                if(booksCollection!=value)
                {
                    booksCollection = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }
    }

    public class SizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double d = 0;
            if(double.TryParse(value?.ToString(), out d))
            {
                return d / 2;
            }
            return d;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

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

        public string Name { get; set; }

        public string Topic { get; set; }

        public string ImgUrl { get; set; }

        public string ISBN { get; set; }

        public ImageSource ImgSource { get; set; }
    }
}

 

标签:multi,via,MVVM,get,Windows,System,set,using,public
From: https://www.cnblogs.com/Fred1987/p/18523507

相关文章

  • Multi-criteria Token Fusion with One-step-ahead Attention for Efficient Vision T
    对于高效的ViT架构,近期研究通过对剪枝或融合多余的令牌减少自注意力层的二次计算成本。然而这些研究遇到了由于信息损失而导致的速度-精度平衡问题。本文认为令牌之间的不同关系以最大限度的减少信息损失。本文中提出了一种多标准令牌融合(Multi-criteriaTokenFusion),该融合......
  • 【语义分割|代码解析】CMTFNet-4: CNN and Multiscale Transformer Fusion Network 用
    【语义分割|代码解析】CMTFNet-4:CNNandMultiscaleTransformerFusionNetwork用于遥感图像分割!【语义分割|代码解析】CMTFNet-4:CNNandMultiscaleTransformerFusionNetwork用于遥感图像分割!文章目录【语义分割|代码解析】CMTFNet-4:CNNandMultiscale......
  • BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection阅读小结
    BEVDet4D:ExploitTemporalCuesinMulti-camera3DObjectDetectionBEVDet4D:在多相机三维目标检测中利用时间线索摘要背景:单帧数据包含有限信息,限制了基于视觉的多相机3D目标检测性能。BEVDet4D提出:提出BEVDet4D范式,将BEVDet从仅空间的3D扩展到时空4D工作空间。改进:通过......
  • NLP论文速读|DDCoT: Duty-Distinct Chain-of-Thought Prompting for Multimodal Reaso
    论文速读|Duty-distinctchain-of-thoughtpromptingformultimodalreasoninginlanguagemodels论文信息:简介:   论文探讨了如何使大型语言模型(LLMs)在多模态环境中进行复杂的推理,这一直是人工智能系统的长期目标。尽管最近的研究表明,通过模仿人类思维过程的“......
  • 知识图谱与多模态学习的关系研究综述P1(《Knowledge Graphs Meet Multi-Modal Learnin
    文章汉化系列目录文章目录文章汉化系列目录摘要I引言A.动机与贡献B.相关文献综述C.文章结构II初步概述A.知识图谱B.多模态学习C.知识图谱驱动的多模态设置D.多模态知识图谱设置III知识图谱构建A.典型知识图谱构建B.多模态知识图谱(MMKG)构建摘要 知......
  • Unleashing Reasoning Capability of LLMs via Scalable Question Synthesis from Scr
    1.概述LLM的SFT数据合成工作不可避免的可以划分为多个阶段:指令合成响应合成数据筛选。本篇文章采用了传统LLM的训练过程(SFT+DPO)进行数据合成。在领域专有模型(DeepSeekMath7B-RL,Qwen2-Math-7BInstruct)的基础上,指令合成:通过QFT(即SFT)使得模型能够正确的生成要求的指令,再......
  • Autodesk Maya 2025.3 Multilanguage (macOS, Windows) - 三维动画和视觉特效软件
    AutodeskMaya2025.3Multilanguage(macOS,Windows)-三维动画和视觉特效软件三维计算机动画、建模、仿真和渲染软件请访问原文链接:https://sysin.org/blog/autodesk-maya/查看最新版。原创作品,转载请保留出处。作者主页:sysin.org三维计算机动画、建模、仿真和渲染软件......
  • C# serialize big collection via NewtonSoft.Json
    System.OutOfMemoryExceptionHResult=0x8007000EMessage=Exceptionoftype'System.OutOfMemoryException'wasthrown.Source=mscorlibStackTrace:atSystem.Text.StringBuilder.ToString()atSystem.IO.StringWriter.ToString()atNewto......
  • CommunityToolkit.Mvvm中的Ioc
    什么是Ioc在软件工程中,控制反转(IoC)是一种设计原则,其中计算机程序的自定义编写部分从外部源(例如框架)接收控制流。术语“反转”是历史性的:与过程式编程相比,具有这种设计的软件架构“反转”了控制。在过程式编程中,程序的自定义代码调用可重用库来处理通用任务,但在控制反转的情况下,是......