Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing event args and sender to the RelayCommand

How do you get event sender when using RelayCommand?

like image 696
incognito Avatar asked Jun 03 '10 06:06

incognito


People also ask

What is a RelayCommand?

The RelayCommand and RelayCommand<T> are ICommand implementations that can expose a method or delegate to the view. These types act as a way to bind commands between the viewmodel and UI elements.

What is a Command MVVM?

Commands are an implementation of the ICommand interface that is part of the . NET Framework. This interface is used a lot in MVVM applications, but it is useful not only in XAML-based apps. The ICommand interface specifies three members: The method Execute(object) is called when the command is actuated.

What is ICommand C#?

The ICommand interface is the code contract for commands that are written in . NET for Windows Runtime apps. These commands provide the commanding behavior for UI elements such as a Windows Runtime XAML Button and in particular an AppBarButton .


2 Answers

This is one of those pain-in-the-%¤# answers where I don't actually answer your question, but instead lecture you about what you should be doing differently. So, sorry about that. Here goes:

If you find yourself in a position where you need to get at the sender object in your viewmodel, then you should probably do something different. By referencing, say, a Button or a ListBox in your viewmodel you have made that viewmodel aware of UI concepts that it should not know anything about. My suggestion is to instead hook up to the event in the code-behind page, find out what you need to know about the sender or what-not, and then execute the viewmodel command programmatically. That is also breaking the MVVM "rules", but IMHO it is a much slighter hack than referencing the sender in your viewmodel.

like image 67
Henrik Söderlund Avatar answered Oct 09 '22 04:10

Henrik Söderlund


I was having a similar problem, but only needed to get the EventArgs. Gladly, this was absurdly simple once I found the answer in another thread here at Stack Overflow.

<cmd:EventToCommand Command="{Binding SomeCommand, Mode=OneWay}" PassEventArgsToCommand="True"/>

Once you know about that magic "PassEventArgsToCommand" setting, you're golden. Just use a RelayCommand<type> instead of a plain RelayCommand.

I hope this helps.

like image 32
SlalomScottJ Avatar answered Oct 09 '22 03:10

SlalomScottJ