I can find a lot of command mouse bindings to a button, but what if I want to bind a mousedown event to a binding (MVVM pattern)? I can't find the answer, probably it is something very small I don't see but can someone help me with this?
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>
You could use an interaction trigger:
<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>
Please refer to the following blog post for more information: https://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
You will need to add a reference to System.Windows.Interactivity.dll.
Updated version (package mentioned above is not produced by library author):
See https://devblogs.microsoft.com/dotnet/open-sourcing-xaml-behaviors-for-wpf/ for more details
The above top rated answer requires access to a dll which is only available if you have blend. (if I understand correct) Following some other examples I wrote a behavior which allows you to bind a command (ICommand) property to the UIElement.
Code Below :
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
}
Implementation :
Make sure to add the refrence "behavior" to the page/control/window. Example - xmlns:behavior="clr-namespace:MyWPFApp.Helper.Behavior"
<Border behavior:MouseDownBehavior.MouseDownCommand="{Binding UploadImageMouseDownCommand, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"></Border>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With