Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event in UserControl- WPF

Tags:

wpf

I have a UserControl in my WPF application.
I want to call a click event and do some things when the user clicked the UserControl.
The problem is- the UserControl doesn't have a click event. I searched on the web and found that you can use the MouseLeftButtonUp event. I tried it- but it doesn't respond to my clicks.

like image 682
amitairos Avatar asked Jul 11 '10 08:07

amitairos


2 Answers

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!");
    }
}
like image 146
Guilherme Avatar answered Sep 23 '22 20:09

Guilherme


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

like image 30
Eugene Cheverda Avatar answered Sep 23 '22 20:09

Eugene Cheverda