Click Event in UserControl - WPF

I have a UserControl in my WPF application. I want to trigger a click event and do some action when the user clicked the UserControl button. The problem is that UserControl does not have a click event. I searched the web and found that you can use the MouseLeftButtonUp event. I tried - but it does not respond to my clicks. Any ideas? Thanks!

+6
wpf
source share
3 answers

You did not write what you are trying to do, but if you need a click event, you are probably writing some kind of button (the Button class is actually β€œsomething you can click” with a visual representation in the control template that you can replace)

  • If you need a button with complex content inside - put your user control inside the button
  • If you need a button that does not look like a button, write your own control pattern for the button
  • If you need a button with additional subclass functionality, add additional data / behavior to the code and place the XAML display in style.
+10
source share

I think the PreviewMouseLeftButtonUp (Down) event is better suited for your needs. Then you need to process ClickCount to count the number of clicks, and then raise your own event, on which other controls will know that your control will be clicked. There are many more click processing methods. You should look at this article msdn and this

UPDATE to handle both Click and DoubleClick

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); _myCustomUserControl.MouseLeftButtonUp += new MouseButtonEventHandler(_myCustomUserControl_MouseLeftButtonUp); _myCustomUserControl.MouseDoubleClick += new MouseButtonEventHandler(_myCustomUserControl_MouseDoubleClick); } bool _doubleClicked; void _myCustomUserControl_MouseDoubleClick(object sender, MouseButtonEventArgs e) { _textBlock.Text = "Mouse left button clicked twice"; _doubleClicked = true; e.Handled = true; } void _myCustomUserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (_doubleClicked) { _doubleClicked = false; return; } _textBlock.Text = "Mouse left button clicked once"; e.Handled = true; } } 

To test this example, name your control as _myCustomUserControl and add a TextBlock named _textBlock in your MainWindow.xaml

+3
source share

Why not just use MouseDown?

Put the event in User Control and just do the following:

 private void MyControl_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { MessageBox.Show("Clicked!"); } } 
0
source share

All Articles