如何将参数传递给事件触发器wpf中的方法

实际上我正在尝试在Xaml文件的viewModel中存在的方法UpdateWord(object obj)中传递word文档的名称。因此它将打开word文档。

ViewModel:

Public void UpdateWord(Object obj){

做一点事 ….. ;

}

你可以这样做

     

你可以参考这篇文章了解更多信息: http ://weblogs.asp.net/alexeyzakharov/silverlight-commands-hacks-passing-eventargs-as-commandparameter-to-delegatecommand-triggered-by-eventtrigger

有多种方法可以做到这一点,请看这里 :

  1. 使用WPF工具。 最简单的

添加命名空间:

  • System.Windows.Interactivitiy
  • Microsoft.Expression.Interactions

XAML:

  xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">       

码:

 public void ShowCustomer() { // Do something. } 
  1. 使用MVVMLight。 最困难但最好的做法

安装GalaSoft NuGet包。

在此处输入图像描述

获取名称空间:

  • System.Windows.Interactivity
  • GalaSoft.MvvmLight.Platform

XAML

  xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:cmd="http://www.galasoft.ch/mvvmlight">       

代表代码: 来源

你必须得到Prism MVVM NuGet包。

在此处输入图像描述

 using Microsoft.Practices.Prism.Commands; // With params. public DelegateCommand CommandOne { get; set; } // Without params. public DelegateCommand CommandTwo { get; set; } public MainWindow() { InitializeComponent(); // Must initialize the DelegateCommands here. CommandOne = new DelegateCommand(executeCommandOne); CommandTwo = new DelegateCommand(executeCommandTwo); } private void executeCommandOne(string param) { // Do something here. } private void executeCommandTwo() { // Do something here. } 

没有DelegateCommand的代码: 来源

 using GalaSoft.MvvmLight.CommandWpf public MainWindow() { InitializeComponent(); CommandOne = new RelayCommand(executeCommandOne); CommandTwo = new RelayCommand(executeCommandTwo); } public RelayCommand CommandOne { get; set; } public RelayCommand CommandTwo { get; set; } private void executeCommandOne(string param) { // Do something here. } private void executeCommandTwo() { // Do something here. } 
  1. 使用Telerik EventToCommandBehavior 。 你必须下载它的NuGet包 。 这是一个选择。

XAML:

    

码:

 public ActionCommand DropCommand { get; private set; } this.DropCommand = new ActionCommand(OnDrop); private void OnDrop(DragEventArgs e) { // Do Something }