SST
SST

Reputation: 459

Handling Mouse events in Viewmodel in WPF MVVM project

I am using System.Windows.Interactivity.dll and Microsoft.Expression.Interaction.dll to do event handling in Viewmodel in my MVVM WPF project. below is the code inside my Xaml:

 <ItemsControl ItemsSource="{Binding Path= HeaderList}" Grid.Row="0" Grid.Column="0" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                  <TextBlock   Text="{Binding Text}" Width="100" HorizontalAlignment="Left" >  
                      <i:Interaction.Triggers>
                          <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
                             <ie:CallMethodAction MethodName="PrevMouseDownEventHandler" TargetObject="{Binding}" />
                          </i:EventTrigger>
                       </i:Interaction.Triggers>
                </TextBlock>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

for this I added namespaces in the same Xaml.

 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
 xmlns:ie="http://schemas.microsoft.com/expression/2010/interactions"

and in my viewmodel I have created a method having PrevMouseDownEventHandler name which is same as that of I mentioned as CallMethod inside EventTigger in the Xaml.

On running my application when I presses mouse button on TextBlock event is generated and look for PrevMouseDownEventHandler method and leave me into following exception:

Could not find method named 'PrevMouseDownEventHandler' on object of type 'string' that matches the expected signature.

this method is as below in my ViewModel.

public void PrevMouseMoveEventHandler(object sender, MouseButtonEventArgs e)
    {
        // Some implementation here;  
    }

I don't have any idea where I am going wrong. Except this all the functionalities inside Viewmodel is working fine for me. what would be possible solution for this?

Upvotes: 0

Views: 3011

Answers (2)

benPearce
benPearce

Reputation: 38333

It is looking for the method on the String object you have bound your Text property to.

Basically your data context has changed from the view model to a property of the View Model.

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102753

CallMethodAction is a delegate with no parameters and no return value. So the "handler" (really an action trigger) would have to look like this:

public void PrevMouseMoveEventHandler()
{
    // Some implementation here;  
}

Also, you'll need to bind to the View Model (your current binding points to the current item in the ItemsControl). You could do this using RelativeSource binding:

<ie:CallMethodAction MethodName="PrevMouseDownEventHandler" 
    TargetObject="{Binding Path=DataContext,RelativeSource={RelativeSource AncestorType=ItemsControl}" />

Upvotes: 1

Related Questions