Question

I need to bind the double click event of a textblock (or potentially an image as well - either way, its a user control), to a command in my ViewModel.

TextBlock.InputBindings does not seem to bind correctly to my commands, any help?

Was it helpful?

Solution

Try Marlon Grech's attached command behaviors.

OTHER TIPS

<Button>
<Button.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="YourCommand" />
</Button.InputBindings>
</Button>

http://thejoyofcode.com/Invoking_a_Command_on_a_Double_Click_or_other_Mouse_Gesture.aspx

it's simple let's use the MVVM way: I'm using here MVVM Light which is easy to learn and strong.

1.put the following lines the xmlns declarations :

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"  
xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;
                                   assembly=GalaSoft.MvvmLight.Extras.WPF4"

2.define your textblock just like this:

<textBlock text="Text with event">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="MouseDoubleClick">
         <GalaSoft_MvvmLight_Command:EventToCommand 
                             Command="{Binding Edit_Command}"/>
      </i:EventTrigger>
   </i:Interaction.Triggers>
</textBlock>

3.then write your command code in your viewmodel !!!

ViewModel1.cs

Public RelayCommand Edit_Command
{
   get;
   private set;
}

Public ViewModel1()
{
   Edit_Command=new RelayCommand(()=>execute_me());
}

public void execute_me()
{
   //write your code here
}

I hope that works for you as I have used it in Real ERP application

I also had a similar issue where I needed to bind the MouseDoubleClick event of a listview to a command in my ViewModel.

The simplest solution I came up is putting a dummy button which has the desired command binding and calling the Execute method of the button's command in the eventhandler of the MouseDoubleClick event.

.xaml

 <Button Visibility="Collapsed" Name="doubleClickButton" Command="{Binding Path=CommandShowCompanyCards}"></Button>
                <ListView  MouseDoubleClick="ListView_MouseDoubleClick" SelectedItem="{Binding Path=SelectedCompany, UpdateSourceTrigger=PropertyChanged}" BorderThickness="0" Margin="0,10,0,0" ItemsSource="{Binding Path=CompanyList, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" HorizontalContentAlignment="Stretch" >

codebehind

     private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
            {
                doubleClickButton.Command.Execute(null);
            }

It is not straightforward but it is really simple and it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top