Getting mouse position in MouseDown event
Hi,
I have a very simple UserControl on which I apply in the XAML, and in the ConnectEvent of my root code-behind:
and then:
I'm getting:
However, when I handle the MouseDown event directly in the MyUserControl code, eg,
It works as expected and I'm getting (for example)
What am I doing wrong in the first example? Thanks!
I have a very simple UserControl on which I apply
Code: Select all
MouseDown="OnMouseDownMyUserControl"
Code: Select all
if (eventName == "MouseDown" && handlerName == "OnMouseDownMyUserControl"){
((MyUserControl)source).MouseDown += OnMouseDownMyUserControl;
return true;
}
Code: Select all
void OnMouseDownMyUserControl(object sender, MouseButtonEventArgs args)
{
var _offset = args.GetPosition(sender as MyUserControl);
Console.WriteLine($"X: {_offset.X} Y: {_offset.Y}");
}
Code: Select all
X: 4.591495E-41 Y: 1.277719E-21
Code: Select all
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}");
};
}
}
Code: Select all
X: 89 Y: 306
Re: Getting mouse position in MouseDown event
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:
It seems that args (potentially) loses its state when we await inside the MouseDown event;
Code: Select all
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}");
}
-
sfernandez
Site Admin
- Posts: 2984
- Joined:
Re: Getting mouse position in MouseDown event
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.
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 77 guests