首页 > 其他分享 >WPF MVVM Datagrid Selected Multiple items via behavior interaction.trigger,eventname method name ,im

WPF MVVM Datagrid Selected Multiple items via behavior interaction.trigger,eventname method name ,im

时间:2024-04-30 14:00:51浏览次数:26  
标签:via string MVVM Windows dg System eventname using public

1.Install Microsoft.Xaml.Behaviors.Wpf from Nuget;

2.Add behavior reference in xaml

xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"

3.Pass method to mvvm via behavior,interaction,trigger,eventname,TargetObject,MethodName in xaml

 <DataGrid x:Name="dg" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
               AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
               VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.IsVirtualizing="True"
               EnableColumnVirtualization="True" EnableRowVirtualization="True" 
               VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingPanel.VirtualizationMode="Recycling"
               SelectionMode="Extended">
     <behavior:Interaction.Triggers>
         <behavior:EventTrigger EventName="SelectionChanged" SourceObject="{Binding ElementName=dg}">
             <behavior:CallMethodAction TargetObject="{Binding}" MethodName="OnSelectionChanged"/>
         </behavior:EventTrigger>
     </behavior:Interaction.Triggers>
     <DataGrid.Columns>
</DataGrid>

 

4.Implmented the specified method name "OnSelectionChanged" in mvvm with the same function signature and public accessor

 

public void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var dg = sender as DataGrid;
if(dg!=null && dg.SelectedItems!=null &&dg.SelectedItems.Count>0)
{
List<Book> selectedBooks=dg.SelectedItems.Cast<Book>().ToList();
string selectedJson = JsonConvert.SerializeObject(selectedBooks,Formatting.Indented);
string filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "selectedJson.json");
System.IO.File.WriteAllText(filePath, selectedJson);
System.Diagnostics.Process.Start("notepad.exe", filePath);
}
}

 

 

The whole code

<Window x:Class="WpfApp74.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:WpfApp74" 
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <DataGrid x:Name="dg" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
                      AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                      VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.IsVirtualizing="True"
                      EnableColumnVirtualization="True" EnableRowVirtualization="True" 
                      VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingPanel.VirtualizationMode="Recycling"
                      SelectionMode="Extended">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged" SourceObject="{Binding ElementName=dg}">
                    <behavior:CallMethodAction TargetObject="{Binding}" MethodName="OnSelectionChanged"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <DataGrid.Columns>
                 <DataGridTextColumn Header="Id" Binding="{Binding Id,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                        IsReadOnly="True" Width="Auto"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Header="Title" Binding="{Binding Title,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Header="Topic" Binding="{Binding Topic,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Header="Summary" Binding="{Binding Summary,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    IsReadOnly="True" Width="*"/>
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
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 Newtonsoft.Json;

namespace WpfApp74
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new ViewModel();
            this.DataContext = vm;
        } 
    }

    //Microsoft.Xaml.Behaviors.Wpf
    public class ViewModel : INotifyPropertyChanged
    {
        public ViewModel()
        {
            InitLV();
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if (value != booksCollection)
                {
                    booksCollection = value;
                }
            }
        }
        private void InitLV()
        {
            BooksCollection = new ObservableCollection<Book>();
            for (int i = 0; i < 1000; i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = i + 1,
                    ISBN = $"ISBN_{i + 1}",
                    Name = $"Name_{i + 1}",
                    Summary = $"Summary{i + 1}",
                    Title = $"Title_{i + 1}",
                    Topic = $"Topic{i + 1}",
                });
            }
        }

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

        public void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dg = sender as DataGrid;
            if(dg!=null && dg.SelectedItems!=null &&dg.SelectedItems.Count>0)
            {
                List<Book> selectedBooks=dg.SelectedItems.Cast<Book>().ToList();
                string selectedJson = JsonConvert.SerializeObject(selectedBooks,Formatting.Indented);
                string filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "selectedJson.json");
                System.IO.File.WriteAllText(filePath, selectedJson);
                System.Diagnostics.Process.Start("notepad.exe", filePath);
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string ISBN { get; set; }
        public string Name { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }
}

 

 

 

 

标签:via,string,MVVM,Windows,dg,System,eventname,using,public
From: https://www.cnblogs.com/Fred1987/p/18167908

相关文章

  • WPF pass event method to viewmodel via Interaction:CallMethodAction,TargetObject
    <Windowx:Class="WpfApp71.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.......
  • [Paper Reading] DETR3D: 3D Object Detection from Multi-view Images via 3D-to-2D
    名称DETR3D:3DObjectDetectionfromMulti-viewImagesvia3D-to-2DQueries时间:21.10机构:mit/CMU/StanfordTL;DR一种利用Transformer做E2E的3D目标检测方法,在nuScenes自动驾驶数据集上取得很好效果。Method主要创新点在于2D-to-3DFeatureTransforms模块,细节如图描......
  • 论文笔记-Modeling of dynamic characteristic of particle in transient gas–solid
    对象:气固两相流+数值模拟方法:RCNN=RNN+CNN目标:学习颗粒流的时间和空间不均匀性并预测颗粒动态关注特征:关注颗粒不均匀性对颗粒动力学的独特影响,旨在提出一种基于机器学习的方法来建模颗粒不均匀性和颗粒动力学之间的映射结果:R-CNN模型的预测精度用1-9个时间步长(即1-9ms)的各......
  • Enhancing ID and Text Fusion via Alternative Training in Session-based Recommend
    目录概MotivationAlterRec代码LiJ.,HanH.,ChenZ.,ShomerH.,JinW.,JavariA.andTangJ.EnhancingIDandtextfusionviaalternativetraininginsession-basedrecommendation.2024.概作者“发现”多模态推荐中ID和文本模态的结合做的并不好,于是乎提出......
  • 开源向量数据库比较:Chroma, Milvus, Faiss,Weaviate
    语义搜索和检索增强生成(RAG)正在彻底改变我们的在线交互方式。实现这些突破性进展的支柱就是向量数据库。选择正确的向量数据库能是一项艰巨的任务。本文为你提供四个重要的开源向量数据库之间的全面比较,希望你能够选择出最符合自己特定需求的数据库。什么是向量数据库?向量数......
  • WPF控件:密码框绑定MVVM
    以下是一种使用MVVM模式的方法:首先,在ViewModel中添加一个属性来保存密码,我们可以使用SecureString类型。//密码变量privateSecureString_password;//密码属性,用于获取和设置密码publicSecureStringPassword{get{return_passw......
  • WPF implemented Single Instance via mutex and activated the existed window via
    1.RemoveStartUri="MainWindow.xaml"inApp.xaml;2.IntheApp.xaml.cs,overriveasbelowusingSystem;usingSystem.Collections.Generic;usingSystem.Configuration;usingSystem.Data;usingSystem.Linq;usingSystem.Runtime.InteropServices;usin......
  • WPF关联Mvvm
    WPF在不使用任何框架去关联View和ViewModel的时候,最常用的2种写法是this.DataContext=newMainViewModel();或者<Window.DataContext><viewModels:MainWindowViewModel/></Window.DataContext>而之所以使用模板不起作用,是因为模板是针对UserControl的,例如<DataT......
  • WPF 使用CommunityToolkit.Mvvm进行快速开发
    一、Net框架情况下:NuGet安装CommunityToolkit.Mvvm使用框架可以简洁快速的编辑代码MvvmFoundationViewModel.cs文件内MvvmFoundationViewModel继承ObservableObject属性上添加[ObservableProperty]属性名称第一个字母不要大写,框架会自动生成大写的字段点击查看代码......
  • 借助Messenger实现ViewModel间通信(communitytoolkit-mvvm)
    两个VM:MainViewModel,TestViewModel需求:TestViewModel中发消息到MainViewModel处理写法1:  1.MainViewModel中注册消息处理函数WeakReferenceMessenger.Default.Register<string,string>(this,"AddItem",DoMessage)  2.参数2用于校验,参数3为消息处理函数  3.TestViewM......