开发者

How to pass EventArgument information from view to view model in WPF?

开发者 https://www.devze.com 2022-12-24 16:20 出处:网络
I have ListView control in my application which is binded 开发者_开发技巧to the collection of CustomObject List<CustomObject>. The CustomObject has seperate view. This ListView has seperate view mo

I have ListView control in my application which is binded 开发者_开发技巧to the collection of CustomObject List<CustomObject>. The CustomObject has seperate view. This ListView has seperate view model.

The collection List _customobject is containted in the ListView ViewModel class.

My Query:

I want to invoke a view that show properties of custom object, when user double click on any row of ListView. The ListView double click command is binded to the ListViewDoublClick Command in the view model. The CustomObject is in the event argument of listview double click command. To acheive this I have to pass the custom object ( or an unique id property of custom object through which I can retrieve the custom object from the collection) as command parameter.

Please suggest me the solution!!


The easiest way to do this is to add a double click event handler to the list. Remember: MVVM does not mean no code in the view! It means that the view only handles view concerns. You can make a really good argument that the EventArgs are only meaningful to the view and if you want to pass it to the ViewModel you should only pass the relevant information. If you have to do something like extracting data from an EventArgs to pass it to the ViewModel, that is acceptable and proper... and better than passing the EventArgs down into the ViewModel, IMHO.

(I'm sure I'll get some disagreement on this point, but dealing with UI interaction is a View concern and if the alternative is writing a behavior or using a framework to get a single control working on a single page, remember: YAGNI and Patterns are not Religion.)

Several of the MVVM frameworks allow you to do this (although there is a lot of discussion about if it's a good idea or not). Inparticular, the MVVM Light Toolkit added this a little while ago to support drag and drop (if I remember the blog post correctly).

If you're not using a MVVM framework, I have wound up writing a behavior to allow me to do this if I was going to do the same thing in multiple places. In this case, I usually extract the information I care about from the EventArgs (i.e. you probably don't really want the full event args, but you probably care which item was clicked and maybe a few other bits of data).

0

精彩评论

暂无评论...
验证码 换一张
取 消