我正在使用System.Windows.Interactivity.dll和Microsoft.Expression.Interaction.dll在我的MVVM WPF项目中的Viewmodel中进行事件处理。 下面是我的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>
为此,我在同一个Xaml中添加了名称空间。
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ie="http://schemas.microsoft.com/expression/2010/interactions"
在我的viewmodel中,我创建了一个名为PrevMouseDownEventHandler
的方法,该方法与我在Xaml中的EventTigger中提到的CallMethod相同。
当我在TextBlock上按下鼠标按钮时运行我的应用程序生成事件并查找PrevMouseDownEventHandler
方法并让我进入以下异常:
Could not find method named 'PrevMouseDownEventHandler' on object of type 'string' that matches the expected signature.
此方法如下所示在我的ViewModel中。
public void PrevMouseMoveEventHandler(object sender, MouseButtonEventArgs e)
{
// Some implementation here;
}
我不知道我哪里出错了。 除此之外,Viewmodel内部的所有功能对我来说都很好。 有什么可能解决这个问题?
答案 0 :(得分:1)
CallMethodAction
是一个没有参数且没有返回值的委托。所以“处理程序”(实际上是一个动作触发器)必须如下所示:
public void PrevMouseMoveEventHandler()
{
// Some implementation here;
}
此外,您需要绑定到视图模型(您当前的绑定点指向ItemsControl
中的当前项)。您可以使用RelativeSource
绑定来执行此操作:
<ie:CallMethodAction MethodName="PrevMouseDownEventHandler"
TargetObject="{Binding Path=DataContext,RelativeSource={RelativeSource AncestorType=ItemsControl}" />
答案 1 :(得分:0)
它正在查找已将Text属性绑定到的String对象上的方法。
基本上,您的数据上下文已从视图模型更改为视图模型的属性。