2012-09-26 44 views
0

我正在使用System.Windows.Interactivity.dll和Microsoft.Expression.Interaction.dll在MVVM WPF项目中的Viewmodel中执行事件处理。下面 是我里面的XAML代码:在WPF MVVM项目中处理Viewmodel中的鼠标事件

<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> 

为了这个,我在同一个XAML中添加的命名空间。

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

,在我的视图模型我已经创建了一个具有方法PrevMouseDownEventHandler名称作为我在XAML提到CallMethod内部EventTigger这是一样的。

在运行我的应用程序,当我按下生成的TextBlock的事件鼠标键,寻找PrevMouseDownEventHandler方法,让我到以下异常:

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

这种方法如下在我的视图模型。

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

我不知道我出错的地方。 除了Viewmodel内部的所有功能对我来说都很好。 这将有什么可能的解决方案?

回答

1

CallMethodAction是一个没有参数且没有返回值的委托。因此,“处理程序”(一个真正的动作触发)必须是这样的:

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

此外,你需要绑定到视图模型(当前的绑定点到当前项目中ItemsControl) 。你可以做到这一点使用RelativeSource绑定:

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

以这种方式给我例外无法找到与'MYVIEWMODEL'类型匹配预期签名的对象上名为'PrevMouseDownEventHandler'的方法。 – SST

0

这是找你已绑定你的Text属性为String对象的方法。

基本上,您的数据上下文已从视图模型更改为View Model的属性。

+0

我是WPF的新手,不太了解它,所以如何解决这个问题?任何代码示例? – SST

+0

我认为你可能能够改变你的TargetObject绑定来使用RelativeSource绑定,你想绑定到父 - [link](http://stackoverflow.com/q/84278/4490) – benPearce