Reputation: 478
I wrote a UserControl whith only one shape in it and trying to get focus clicking on it.
It still gets focus using the tab key, but it won't get focus when I click on it.
Even when I code a PointerPressed Event where I set focus programatilly it won't work.
Here is the xaml:
<UserControl GotFocus="GotFocus" LostFocus="LostFocus" IsTabStop="True">
<Rectangle x:Name="rect"/>
</UserControl>
and the code:
private void GotFocus(object sender, RoutedEventArgs e)
{
rect.Fill = new Windows.UI.Xaml.Media.SolidColorBrush(Colors.Aqua);
}
private void LostFocus(object sender, RoutedEventArgs e)
{
rect.Fill = new Windows.UI.Xaml.Media.SolidColorBrush(Colors.Beige);
}
Has anybody got an idea?
Edit:
I am working with Windows 8.1 and VisualStudio 2013.
Maybe it's a new feature^^
Upvotes: 1
Views: 1346
Reputation: 1947
From the debugger, it looks like the UserControl is indeed getting the GotFocus event when you click on it but then is immediately losing focus. It seems the reason it loses focus is that the PointerReleased event continues routing out the visual tree and goes to the root ScrollViewer (all XAML apps have a ScrollViewer at the root of the tree to allow app content to scroll when the on-screen keyboard shows).
I think this behavior could be considered by design. If you put a UserControl inside the template of another control (e.g. Button), you may want the PointerReleased event to continue routing up the tree to the templated parent (i.e. so the Button.Click event still fires).
If you want your UserControl to keep focus when the user clicks on it, you need to handle the PointerReleased event yourself. Add a handler for it like so:
XAML:
<UserControl PointerReleased="UserControl_PointerReleased" />
Code Behind:
private void UserControl_PointerReleased(object sender, PointerRoutedEventArgs e)
{
((UserControl)sender).Focus(FocusState.Pointer);
e.Handled = true;
}
Example code is available here: https://github.com/finnigantime/Samples/tree/master/examples/Win8Xaml/UserControl_FocusExample
Upvotes: 4