I have listview and I want to have show new window when someone double click in any position. But I have mvvm application and I don't want to have any function in code behind of xaml file, like this: How to bind a Command to double-click on a row in DataGrid and many other samples like this. I want to have method in viewmodel file and bind it like this:
<ListView ... MouseDoubleClick="{Binding myfunction}">
Thanks
This is a working example of a method to trigger a command (In the ViewModel) based on the clicked item in a list. The command in the ViewModel will get the "clicked" item as its parameter.
I'm using the Textblock.InputBindings and that might be part of the Blend SDK linked by Blachshma, but you will not need any other DLLs for this to work.
In my example the ViewModel is bound to the DataContext of the UserControl, that is why I need to use the RelativeSource FindAncestor to find the ViewModel from my TextBlock.
Edit: Fixed the width problem by binding the Width of the TextBlock to the ActualWidth of the ListBox.
Just one problem, the double click will only work when you click inside the text in the textblock even if the list itself is much wider.The easiest way to do this is to use
System.Windows.Interactivity
andMicrosoft.Expression.Interactions
(both freely available through the Blend SDK)So start by adding the following namespaces to your view
Next, catch the DoubleClick event and pass it to the command:
Note: The
EventToCommand
used is the one from the MVVM Light Toolkit and can be downloaded here. What it does is execute the command (myFunction
) as soon as the event is triggered.This is based on the assumption that the
myFunction
command is in the DataContext which the ListView users. Otherwise, modify the binding of the EventToCommand to wherever the command is.You can use Attached Properties to bind any event you want.
For
MouseDoubleClick
:And in Xaml: