MVVM Light: Adding EventToCommand in XAML without Blend, easier way or snippet?

霸气de小男生 提交于 2019-11-26 15:24:42

Suppose you use .NetFramework4:

First add namespace:

xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"

Syntax for the Loaded event.

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=LoadedCommand}"
                            PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>

I updated my project and it looks like they moved the command to:

xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"

0) if you dont't know WPF and MVVM, then read Josh Smith article about WPF and MVVM pattern https://msdn.microsoft.com/en-us/magazine/dd419663.aspx

1) In your project add package (through NuGet) MvvmLightLibs

2) add reference to System.Windows.Interactivity

3) In "View" XAML add:

a)

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:command="http://www.galasoft.ch/mvvmlight"

b)

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
      <command:EventToCommand Command="{Binding OnClosingCommand}"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Window>

4) In ViewModel add necessary property

public ICommand OnClosingCommand
{
  get
  {
    return new RelayCommand(() => SomeMethod());
  }
}

P.S. In your View should be specified DataContext (XAML)

  <Window.DataContext>
    <vm:MainWindowViewModel/>
  </Window.DataContext>

It is work. I myself just learned.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!