2011-03-28 108 views
7

問題:導航與製表鍵停止在摺疊TextBlock /超鏈接。WPF:製表導航折斷超鏈接

繁殖:

<Window x:Class="TabTest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Width="200" Height="200"> 

    <Grid> 
     <StackPanel Orientation="Vertical"> 
      <TextBox Text="before" /> 
      <TextBlock> 
       <TextBlock.Style> 
        <Style TargetType="{x:Type TextBlock}"> 
         <Setter Property="Visibility" Value="Collapsed"/> 
        </Style> 
       </TextBlock.Style> 
       <Hyperlink Focusable="False"> 
        <TextBlock Text="test" /> 
       </Hyperlink> 
      </TextBlock> 
      <TextBox Text="after" /> 
     </StackPanel> 
    </Grid> 
</Window> 

如果你運行這個超級簡單的演示,然後按TAB,將光標移動到「之前」文本框。再次按TAB確實沒有任何結果。光標停留在「之前」文本框,並且永遠不會到達「之後」文本框。當超鏈接的TextBlock可見時,導航按預期工作。

問題:如何使HyperLink摺疊後TAB導航正常工作?

回答

8

問題不在於超鏈接,而在於TextBlock中的嵌套控件。您可以將其更改爲

<TextBlock Visibility="Collapsed">    
    <TextBlock Text="MyText" /> 
</TextBlock> 

並且Tab導航仍將被打破。

的解決方案是在外部的TextBlock使用KeyboardNavigation.TabNavigation="Once"

<TextBlock KeyboardNavigation.TabNavigation="Once"> 
    <TextBlock.Style> 
     <Style TargetType="{x:Type TextBlock}"> 
      <Setter Property="Visibility" Value="Collapsed"/> 
     </Style> 
    </TextBlock.Style> 
    <Hyperlink Focusable="False"> 
     <TextBlock Text="test" /> 
    </Hyperlink> 
</TextBlock> 

然後一切按預期工作的方式。問題是內部TextBlock獲取焦點,即使外部控制它被摺疊。將KeyboardNavigation.TabNavigation設置爲Once可以解決整個容器及其孩子只能關注一次的問題。 (MSDN

+0

簡單而有效的;-)謝謝! – 2011-03-28 18:49:04

2

@ Gimno的回答讓我在正確的軌道上,但是我發現,使用KeyboardNavigation.TabNavigation="None",其實是給予頂部元素焦點只有一次(因爲你會從Once期望)。 Gimno的回答是有效的,因爲他/她也在超鏈接上設置了Focusable="False"。使用TabNav = None,您不必在所有子控件上設置Focusable。

這裏是我的這種方法的應用(僅Button獲取標籤的重點,也不正文塊或超鏈接):

<Button Command="{Binding ChangeSoundCommand}" Click="ChangeSoundClick" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Transparent" BorderBrush="Transparent" BorderThickness="0" Padding="0" 
KeyboardNavigation.TabNavigation="None"> 
    <Button.Template> 
     <ControlTemplate> 
      <Grid> 
       <TextBlock Name="tb" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Collapsed" > 
        <Hyperlink>Browse...</Hyperlink> 
       </TextBlock> 
       <TextBlock Name="w_content" Text="{Binding FilePath}" TextTrimming="CharacterEllipsis" /> 
      </Grid> 
      <ControlTemplate.Triggers> 
       <Trigger SourceName="w_content" Property="Text" Value=""> 
        <Setter TargetName="tb" Property="Visibility" Value="Visible"/> 
       </Trigger> 
      </ControlTemplate.Triggers> 
     </ControlTemplate> 
    </Button.Template> 
</Button>