我可以找到很多命令鼠标绑定到按钮,但如果我想将mousedown事件绑定到绑定(MVVM模式)怎么办?我找不到答案,可能是我看不到的东西很小但有人可以帮我这个吗?
XAML:
<DataTemplate>
<Grid AllowDrop="True">
<Rectangle Width="100" Height="50" RadiusX="4" RadiusY="4" Fill="LightBlue"/>
<Label Content="{Binding EntityName}" MouseDown="{Binding DoSomething}"/>
</Grid>
</DataTemplate>
您可以使用交互触发器:
<Label Content="{Binding EntityName}" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown" >
<i:InvokeCommandAction Command="{Binding DoSomething}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Label>
有关更多信息,请参阅以下博客文章:https://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
您需要添加对System.Windows.Interactivity.dll的引用。
以上评分最高的答案需要访问dll,只有混合后才能使用。 (如果我理解正确的话)在其他一些例子中,我编写了一个行为,允许您将命令(ICommand)属性绑定到UIElement。
代码如下:
public static class MouseDownBehavior
{
#region Dependecy Property
private static readonly DependencyProperty MouseDownCommandProperty = DependencyProperty.RegisterAttached
(
"MouseDownCommand",
typeof(ICommand),
typeof(MouseDownBehavior),
new PropertyMetadata(MouseDownCommandPropertyChangedCallBack)
);
#endregion
#region Methods
public static void SetMouseDownCommand(this UIElement inUIElement, ICommand inCommand)
{
inUIElement.SetValue(MouseDownCommandProperty, inCommand);
}
private static ICommand GetMouseDownCommand(UIElement inUIElement)
{
return (ICommand)inUIElement.GetValue(MouseDownCommandProperty);
}
#endregion
#region CallBack Method
private static void MouseDownCommandPropertyChangedCallBack(DependencyObject inDependencyObject, DependencyPropertyChangedEventArgs inEventArgs)
{
UIElement uiElement = inDependencyObject as UIElement;
if (null == uiElement) return;
uiElement.MouseDown += (sender, args) =>
{
GetMouseDownCommand(uiElement).Execute(args);
args.Handled = true;
};
}
#endregion
}
实施:
确保将引用“behavior”添加到页面/控件/窗口。示例 - xmlns:behavior =“clr-namespace:WPF App.Helper.Behavior”
<Border behavior:MouseDownBehavior.MouseDownCommand="{Binding UploadImageMouseDownCommand, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"></Border>