Reputation: 2719
This is a related to SO Question 3222456 ....
I'm creating my own UserControl with a few images and TextBlock's on it, nothing else. I'd like to fire an event when the whole UserControl is clicked. My problem (or misunderstanding) is that in WPF there only seem to be MouseUp events that I can hook into, no MouseClick.
So what's the best practice? All the examples I can find act as if a mouseUp in WPF is equivalent to a click event but that's not right. What if the user did a mouseDown in one part of the screen, held the mouse until it was over my control, and then released the mouse. That's not a click of my control even though it fires a MouseUp event.
So how do I get a true MouseClick event for my UserControl?
Upvotes: 2
Views: 4817
Reputation: 5341
Why not just use MouseDown?
Put the event in the User Control and simply do this:
private void MyControl_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
MessageBox.Show("Clicked!");
}
}
Upvotes: 2
Reputation: 25563
One very easy way would be to put your entire content into a button with an almost empty template and respond to the Button
's OnClick
event.
This would look like
Old:
<UserControl ...>
<Grid> ... </Grid>
</UserControl>
New:
<UserControl ...>
<Button OnClick="YourEventHandler">
<Grid> ... </Grid>
<Button.Template>
<ControlTemplate x:Key="BlankButtonTemplate" TargetType="{x:Type ButtonBase}">
<Border Background="#00000000">
<ContentPresenter Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</UserControl>
Upvotes: 4