Reputation: 127
I'm attempting to create an MVVM WPF application that allows me to draw a rectangle in the window. Right now, I've created a canvas element that covers the entire screen. Following other questions and guides, it looks like the only way to use command bindings on mouse events (such as MouseDown
, MouseUp
, etc) is to use the System.Windows.Interactivity assembly and add EventTriggers for the mouse events. However, this doesn't seem to be working with the canvas element. Clicking, click/hold, click/drag, right clicking, none of them trigger the Execute method of my command.
What are the supported events for a canvas element? Why would MouseDown
or PreviewMouseDown
not be working?
XAML for the window:
<Window x:Class="RutheniumReader.SnippingWindow.SnippingShade"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:snippingWindow="clr-namespace:MyApp.SnippingWindow"
mc:Ignorable="d"
Title="Snipping Window"
WindowState="Maximized"
Background="Black"
>
<Window.DataContext>
<snippingWindow:SnippingWindowViewModel />
</Window.DataContext>
<Canvas x:Name="Canvas">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<i:InvokeCommandAction Command="{Binding Path=MouseDownCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Canvas>
</Window>
For testing purposes, I've tried the following events with no luck:
Button
element inside the canvasButton
elementUpvotes: 3
Views: 8554
Reputation: 481
The mouse events aren't working because the canvas's background isn't set.
If a control (in this case your Canvas
) has no background color set, the background color will default to null, and that makes the control non hit-testable.
The background can be set either explicitly or through styles, and as long as it has a value different from null
(even 'Transparent') it should pickup mouse events.
Upvotes: 7