Passing event args and sender to the RelayCommand

泄露秘密 提交于 2019-12-18 05:46:11

问题


How do you get event sender when using RelayCommand?


回答1:


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.




回答2:


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.




回答3:


This can be done by binding the sender to the Command Parameter.

<command:EventToCommand
              Command="{Binding CommandName}"
              CommandParameter="{Binding RelativeSource=
                                         { RelativeSource FindAncestor, 
                                           AncestorType={x:Type TypeOfSender},
                                           AncestorLevel=1}}" 
              PassEventArgsToCommand="True" >
</command:EventToCommand>


来源:https://stackoverflow.com/questions/2963830/passing-event-args-and-sender-to-the-relaycommand

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