Wegel
Topic Author
Posts: 4
Joined: 04 Apr 2019, 16:16

Getting mouse position in MouseDown event

07 Apr 2019, 03:18

Hi,

I have a very simple UserControl on which I apply
MouseDown="OnMouseDownMyUserControl"
in the XAML, and in the ConnectEvent of my root code-behind:
if (eventName == "MouseDown" && handlerName == "OnMouseDownMyUserControl"){
   ((MyUserControl)source).MouseDown += OnMouseDownMyUserControl;
   return true;
 }
and then:
void OnMouseDownMyUserControl(object sender, MouseButtonEventArgs args)
{
   var _offset = args.GetPosition(sender as MyUserControl);
   Console.WriteLine($"X: {_offset.X} Y: {_offset.Y}");
}
I'm getting:
X: 4.591495E-41 Y: 1.277719E-21
However, when I handle the MouseDown event directly in the MyUserControl code, eg,
public class MyUserControl: UserControl
{
    public MyUserControl()
    {
        this.MouseDown += (s, e) => {
                var _offset = e.GetPosition(s as Blargh);
                Console.WriteLine($"X: {_offset.X} Y: {_offset.Y}");
            };
    }
}
It works as expected and I'm getting (for example)
X: 89 Y: 306
What am I doing wrong in the first example? Thanks!

Tags:
 
Wegel
Topic Author
Posts: 4
Joined: 04 Apr 2019, 16:16

Re: Getting mouse position in MouseDown event

07 Apr 2019, 17:01

I think I found the culprit. In the version that binds the event from ConnectEvent, the handling function is marked as async, and I was doing something similar to:
async void OnMouseDownMyUserControl(object sender, MouseButtonEventArgs args)
{
   await doSomeAsyncStuff();
   var _offset = args.GetPosition(sender as MyUserControl);
   Console.WriteLine($"From Window X: {_offset.X} Y: {_offset.Y}");
}
It seems that args (potentially) loses its state when we await inside the MouseDown event;
 
User avatar
sfernandez
Site Admin
Posts: 1918
Joined: 22 Dec 2011, 19:20

Re: Getting mouse position in MouseDown event

07 Apr 2019, 17:53

That's right, event handlers cannot be executed asynchronously.
Also remark that the View and its UI tree cannot be modified from a different thread than the one used to create it.

Who is online

Users browsing this forum: No registered users and 1 guest