問題描述
我們有一個基于 WPF .NET 4.0 C# 的應用程序.我們從 XML 定義(不是 XAML)構建我們的用戶界面,但在下面我們使用 WPF 來呈現 UI.也就是說,在運行時,我們基于 XML 定義創建 WPF UI.
We have a WPF .NET 4.0 C# based application. We built our user interface from XML definitions (not XAML) but underneath we use a WPF to present the UI. That is at runtime, we create the WPF UI based on our XML definition.
標簽導航有問題.我們為文本和組合框控件設置了 TabStop、TabIndex.
但是標簽導航不起作用.如何使標簽導航適用于此布局?
We have a problem with tab navigation. We set TabStop, TabIndex, for text and combo box controls.
But tab navigation is not working. How to make tab navigation work for this layout?
推薦答案
WPF 將整個 UI 樹視為單個 Tab 范圍.它不會像您期望的那樣分解成更小的區域.這包括 UserControls 中的控件.
WPF treats the entire UI Tree as a single Tab scope. It isn't broken up into smaller areas such as you would expect. This includes controls inside UserControls.
例如,如果你有
<StackPanel>
<TextBox Name="TextBox1" />
<MyUserControl />
<TextBox Name="TextBox3" />
</StackPanel>
而 MyUserControl
看起來像
<MyUserControl>
<TextBox Name="TextBox2" />
</MyUserControl>
默認選項卡循環為 TextBox1、TextBox2、TextBox3.這是因為沒有定義 TabIndex 屬性,所以所有控件都以默認的 Tab 鍵順序運行,也就是它們添加到 UI 中的順序.
The default tab cycle would be TextBox1, TextBox2, TextBox3. This is because no TabIndex properties are defined, so all controls run at the default tab order, which is the order in which they're added to the UI.
如果您在控件上設置 TabIndex,如下所示,
If you set the TabIndex on your controls such as below,
<StackPanel>
<TextBox Name="TextBox1" TabIndex="1" />
<MyUserControl TabIndex="2" />
<TextBox Name="TextBox3" TabIndex="3" />
</StackPanel>
您的制表符將更改為 TextBox1、TextBox3、TextBox2.這是因為 TextBox2 沒有指定 TabIndex,因此假定為默認值,并且在所有其他指定了 TabIndex 的控件循環通過之后,它會被選項卡化.
Your tabbing would change to TextBox1, TextBox3, TextBox2. This is because TextBox2 doesn't have a TabIndex specified, so the default is assumed and it is tabbed to after all the other controls with a TabIndex specified get cycled through.
我通常解決這個問題的方法是將 UserControl 內控件的 TabIndex
綁定到 UserControl.TabIndex.
The way I usually get around this is to bind the TabIndex
of controls inside the UserControl to the UserControl.TabIndex.
例如,將以下綁定添加到 UserControl 將使 Tab 循環再次正確
For example adding the following binding to the UserControl would make the Tab cycle correct again
<MyUserControl>
<TextBox Name="TextBox2" TabIndex="{Binding Path=TabIndex, RelativeSource={RelativeSource AncestorType={x:Type local:MyUserControl}}}" />
</MyUserControl>
我通常更喜歡在 UserControl 的 Loaded
事件中設置此綁定,而不必記住在 UserControl 內的所有控件上設置此綁定.我相信還有更有效的方法可以做到這一點,但是問題出現的頻率還不夠高,讓我坐下來花時間研究如何正確使用選項卡范圍以避免這種解決方法.
I usually prefer to set this binding in the Loaded
event of the UserControl instead of having to remember to set this binding on all the controls inside the UserControl. I'm sure there are also more efficient ways of doing this as well, however the problem has not come up often enough for me to sit down and take the time to research how to use tab scopes correctly to avoid this workaround.
這篇關于WPF 選項卡鍵導航的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!