你需要设置IsTabStop="True"
让它聚焦。UserControl's
默认为假。
您需要做的另一件事是显示一个焦点指示器,您不能UserControl
免费获得它。这是您可以为其添加视觉效果的方式 - 从Button
模板复制:
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup
x:Name="FocusStates">
<VisualState
x:Name="Focused">
<Storyboard>
<DoubleAnimation
Duration="0"
To="1"
Storyboard.TargetProperty="Opacity"
Storyboard.TargetName="FocusVisualWhite" />
<DoubleAnimation
Duration="0"
To="1"
Storyboard.TargetProperty="Opacity"
Storyboard.TargetName="FocusVisualBlack" />
</Storyboard>
</VisualState>
<VisualState
x:Name="Unfocused" />
<VisualState
x:Name="PointerFocused" />
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle
x:Name="FocusVisualWhite"
IsHitTestVisible="False"
Opacity="0"
StrokeDashOffset="1.5"
StrokeEndLineCap="Square"
Stroke="{ThemeResource FocusVisualWhiteStrokeThemeBrush}"
StrokeDashArray="1,1" />
<Rectangle
x:Name="FocusVisualBlack"
IsHitTestVisible="False"
Opacity="0"
StrokeDashOffset="0.5"
StrokeEndLineCap="Square"
Stroke="{ThemeResource FocusVisualBlackStrokeThemeBrush}"
StrokeDashArray="1,1" />
</Grid>
您仍然需要切换视觉状态,因此您可以执行以下操作:
protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
this.UpdateVisualState(true);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
this.UpdateVisualState(true);
}
private void UpdateVisualState(bool useTransitions)
{
switch (this.FocusState)
{
case FocusState.Programmatic:
case FocusState.Keyboard:
VisualStateManager.GoToState(this, "Focused", useTransitions);
break;
case FocusState.Pointer:
VisualStateManager.GoToState(this, "PointerFocused", useTransitions);
break;
case FocusState.Unfocused:
VisualStateManager.GoToState(this, "Unfocused", useTransitions);
break;
}
}