2017-02-09 49 views
1

我正在用觸摸屏爲RPi3構建一個UWP應用程序。我有一個文本框,我將重點放在頁面加載上。如果用戶觸摸頁面上的另一個控件(除了兩個特定按鈕),我不想失去焦點。我正在使用此文本框進行掃描儀輸入。在UWP中禁用焦點控制

我試圖禁用,因爲我不想獲得焦點的控件不同的屬性:

AllowFocusOnInteraction="False" IsDoubleTapEnabled="False" IsHitTestVisible="False" IsHoldingEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False" 

但是,如果我按任何這些控件,文本框劇照失去焦點。

我也嘗試過一個textbox_LostFocus的事件處理程序重新給它的焦點,但是這會阻止用戶單擊一個用戶需要單擊的2個按鈕(唯一控制誰應該接收焦點)作爲textbox_LostFocus事件在button_Click事件觸發前再次觸發焦點回到文本框。

在一個winform中,我會禁用tabstop屬性。 UWP的任何想法?

在此先感謝。

回答

1

如果你希望你的文本框不會失去焦點,你應該能夠通過Focus方法在LostFocus設置對焦事件。

如您所知,如果我們在LostFocus事件中設置Focus,則無法觸發Click事件。

因此,我們應該可以在您的LostFocus事件中添加if,當用戶單擊按鈕時,文本可能會失去焦點。爲此,我們可以添加PointerEntered事件和ButtonPointerExited。在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; 
} 
0

上的按鈕,你不想注重,嘗試IsTabStop屬性設置爲false

+0

(此屬性也是UWP) – PrisonMike

+1

[IsTabStop](https://docs.microsoft.com/en-us/uwp/api/Windows.UI。 Xaml.Controls.Control#Windows_UI_Xaml_Controls_Control_IsTabStop)*「表示控件是否包含在標籤導航中。」*換句話說,它控制**鍵盤導航。這不是問題的要求。 – IInspectable

+0

哦,我以爲他的意思是鍵盤焦點,因爲如果他們沒有焦點是不可能按下按鈕,他還說,在winforms中,他會使用isTabStop屬性,所以我只是指出這也是可用的在uwp – PrisonMike

1

IsEnabled property做到這一點。如果你不喜歡「變灰」的外觀,你可以改變控制模板。

1

我和你有類似的問題。

解決方案在我的情況被設定根視覺元素(ScrollViewer中)財產AllowFocusOnInteraction爲false:

var rootScrollViewer = GetVisualRootElement(); 
rootScrollViewer.AllowFocusOnInteraction = false; 

我的視覺樹是這個樣子:ScrollViewer-> Border->幀 - > MainPage-> StackPanel-> etc ...

下一步是將AllowFocusOnInteraction設置爲True來控制你想要允許關注交互(TextBox,CheckBox等等)。

此致

亞當