In a WPF application using MVVM, I have a usercontrol with a listview item. In run time, it will use databinding to fill the listview with a collection of objects.
What is the correct way to attach a double click event to the items in the listview so that when an item in the list view is doubleclicked, A corresponding event in the view model is fired and has a reference to the item clicked?
How can it be done in a clean MVVM way i.e. no code behind in the View?
I saw the solution from rushui with the InuptBindings but I was still unable to hit the area of the ListViewItem where there was no text - even after setting the background to transparent, so I solved it by using different templates.
This template is for when the ListViewItem has been selected and is active:
This template is for when the ListViewItem has been selected and is inactive:
This is the Default style used for the ListViewItem:
What I don't like is the repetition of the TextBlock and its text binding, I don't know I I can get around declaring that in just the one location.
I hope this helps someone!
Please, code behind is not a bad thing at all. Unfortunately, quite a lot people in the WPF community got this wrong.
MVVM is not a pattern to eliminate the code behind. It is to separate the view part (appearance, animations, etc.) from the logic part (workflow). Furthermore, you are able to unit test the logic part.
I know enough scenarios where you have to write code behind because data binding is not a solution to everything. In your scenario I would handle the DoubleClick event in the code behind file and delegate this call to the ViewModel.
Sample applications that use code behind and still fulfill the MVVM separation can be found here:
WPF Application Framework (WAF) - http://waf.codeplex.com