首页 > 其他分享 >WPF pass event method to viewmodel via Interaction:CallMethodAction,TargetObject MethodName

WPF pass event method to viewmodel via Interaction:CallMethodAction,TargetObject MethodName

时间:2024-04-29 14:23:37浏览次数:17  
标签:CallMethodAction via MethodName get Windows System set using public

<Window x: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.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp71"
        mc:Ignorable="d"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:interaction="http://schemas.microsoft.com/expression/2010/interactions"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="dg" Grid.Row="1" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
VerticalAlignment="Stretch" HorizontalAlignment="Stretch" BorderBrush="Blue"
 BorderThickness="3" SelectionMode="Extended"
SelectedItem="{Binding SelectedBook,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <interaction:CallMethodAction TargetObject="{Binding}" MethodName="OnSelectionChanged"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </DataGrid>
    </Grid>
</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;

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

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

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

    public class MainVM:ModelBase
    {
        public MainVM()
        {
            InitLV();
        }
        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}",
                });
            }
        }

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

        public void OnSelectionChanged(object sender,SelectionChangedEventArgs e)
        {
            var dg = sender as DataGrid;
            var selectedItems = e.AddedItems;
            StringBuilder builder = new StringBuilder();
            foreach(var item in selectedItems) 
            {
                var bk= item as Book;
                if(bk!=null)
                {
                    builder.AppendLine($"Id:{bk.Id},Name:{bk.Name}");
                } 
            }

            System.Windows.MessageBox.Show($"{builder.ToString()}", $"Selected {selectedItems.Count} items", MessageBoxButton.OK);
        }
    }

}

 

Key part

1.Install System.Windows.Interactivity.WPF from nuget;

2.Add interactivity and interactivity in xaml

3.Pass event method to viewmodel via interaction:CallMethodAction and specified MethodName

 <i:Interaction.Triggers>
     <i:EventTrigger EventName="SelectionChanged">
         <interaction:CallMethodAction TargetObject="{Binding}" MethodName="OnSelectionChanged"/>
     </i:EventTrigger>
 </i:Interaction.Triggers>

4.Implemented the MethodName in viewmodel with same signature as event method in xaml.cs

 public void OnSelectionChanged(object sender,SelectionChangedEventArgs e)

 

Be cautious,the Method's accessor must be public

标签:CallMethodAction,via,MethodName,get,Windows,System,set,using,public
From: https://www.cnblogs.com/Fred1987/p/18165627

相关文章

  • [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 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......
  • 大型场景中通过监督视图贡献加权进行多视图人物检测 Multi-View People Detection in
    Multi-ViewPeopleDetectioninLargeScenesviaSupervisedView-WiseContributionWeighting大型场景中通过监督视图贡献加权进行多视图人物检测论文urlhttps://ojs.aaai.org/index.php/AAAI/article/view/28553论文简述:这篇论文提出了一个用于大型场景中多视角人体检测......
  • C++要点细细梳理——trivial:运算符优先级、switch、临时变量默认赋值等
    1.运算符优先级在C语言中,运算符的优先级决定了在表达式中各个运算符的执行顺序。当一个表达式中有多个运算符时,优先级高的运算符会先被计算。如果两个运算符的优先级相同,那么它们的结合性(从左到右或从右到左)会决定它们的计算顺序。以下是一些基本的C语言运算符优先级(从......
  • RuleEngine规则引擎底层改造AviatorScript 之函数执行
    https://gitee.com/aizuda/rule-engine-open需求:使用上述开源框架进行改造,底层更换成AviatorScript,函数实现改造。原本实现方式@OverridepublicObjectrun(ExecuteFunctionRequestexecuteTestRequest){IntegerfunctionId=executeTestRequest.ge......
  • WPF datagrid mvvm multi select via customize datagrid
    usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows;usingSystem.Windows.Controls;namespaceWpfApp39{publicclassMultiSelectDataGrid:D......
  • DMKD: IMPROVING FEATURE-BASED KNOWLEDGE DISTILLATION FOR OBJECT DETECTION VIA DU
    摘要最近主流的掩模蒸馏方法是通过从教师网络的特征图中重建学生网络的选择性掩模区域来实现的。在这些方法中,需要适当的选择掩模区域,使重构的特征像教师特征一样具有足够的识别和表示能力。然而,以前的掩模蒸馏方法只关注空间掩模,使得得到的掩模区域偏向于空间重要性,而没有......