Wednesday, September 10, 2008

Silverlight Tip 4#: How to detect user clicks outside of your control

In order to do this you may find application root and add mouse click event handler to it:


private void MyControl_Loaded(object sender, RoutedEventArgs e)
{
...

//root
FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
if (root != null)
{
root.MouseLeftButtonDown += new MouseButtonEventHandler(root_MouseLeftButtonDown);
}
}

and check when user clicks:


void root_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
double x = e.GetPosition(this).X;
double y = e.GetPosition(this).Y;

if (x < 0 || x > this.ActualWidth || y < 0 || y > this.ActualHeight)
{
//to do
}
}

But this is not ideal solution, because it doesn't work when you click outside your control and on the control which handles MouseLeftButtonDown event (for example Button). For more information see: http://silverlight.net/forums/p/23071/82288.aspx

No comments: