如果你希望你的文本框不會失去焦點,你應該能夠通過Focus
方法在LostFocus
設置對焦事件。
如您所知,如果我們在LostFocus
事件中設置Focus
,則無法觸發Click
事件。
因此,我們應該可以在您的LostFocus
事件中添加if
,當用戶單擊按鈕時,文本可能會失去焦點。爲此,我們可以添加PointerEntered
事件和Button
的PointerExited
。在PointerEntered
事件中,我們可以設置值setFocus
。
例如:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Content="Click" AllowFocusOnInteraction="False" IsDoubleTapEnabled="False" IsHitTestVisible="False" IsHoldingEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False"></Button>
<TextBox Name="MyText" Text="Hello" LostFocus="MyText_LostFocus"></TextBox>
<Button Name="MyButton" PointerEntered="MyButton_PointerEntered" PointerExited="MyButton_PointerExited" Click="Button_Click" Content="Submit"></Button>
</StackPanel>
</Grid>
後面的代碼:
private bool setFocus = true;
private void MyText_LostFocus(object sender, RoutedEventArgs e)
{
if (setFocus == true)
{
MyText.Focus(FocusState.Programmatic);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyButton.Focus(FocusState.Programmatic);
}
private void MyButton_PointerEntered(object sender, PointerRoutedEventArgs e)
{
setFocus = false;
}
private void MyButton_PointerExited(object sender, PointerRoutedEventArgs e)
{
setFocus = true;
}
(此屬性也是UWP) – PrisonMike
[IsTabStop](https://docs.microsoft.com/en-us/uwp/api/Windows.UI。 Xaml.Controls.Control#Windows_UI_Xaml_Controls_Control_IsTabStop)*「表示控件是否包含在標籤導航中。」*換句話說,它控制**鍵盤導航。這不是問題的要求。 – IInspectable
哦,我以爲他的意思是鍵盤焦點,因爲如果他們沒有焦點是不可能按下按鈕,他還說,在winforms中,他會使用isTabStop屬性,所以我只是指出這也是可用的在uwp – PrisonMike