Click event in UserControl- WPF

You didn't write what you are trying to do but if you need a click event maybe you are writing some kind of button (the Button class is actually "something you can click" with the visual representation in a control template you can replace)

  • If you need a button with complex content inside - put your user control inside a button
  • If you need a button that doesn't look like a button write a custom control template for button
  • If you need a button with extra functionality subclass button, add the extra data/behavior in code and put the display XAML in a style.

I think for your needs PreviewMouseLeftButtonUp(Down) event is more suitable. Then you need to handle ClickCount for counting amount of clicks and then raise your own event, on which other controls will know, that your control is clicked. There are much more methods on handling click event. You should look at this msdn article 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 to your MainWindow.xaml


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!");
    }
}

Tags:

Wpf