按Tab键wpf时出错

时间:2014-03-10 21:54:23

标签: c# wpf

我有一个包含2个字段的简单窗口:

<TextBox Grid.Column="1" HorizontalAlignment="Left" Height="21" Margin="10,25,0,0" Grid.Row="1" Name="textbox_login" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="227" KeyDown="textbox_login_KeyDown"/>
            <PasswordBox Grid.Column="1" HorizontalAlignment="Left" Height="22" Margin="10,25,0,0" Grid.Row="2" Name="passwordBox_mdp" VerticalAlignment="Top" Width="227" KeyDown="passwordBox_mdp_KeyDown"/>

当我按下键盘上的Tab键时,我可以切换到下一个字段,但是如果我再次按下该键,我就会到达最后一个字段,我在#34; MyApplication.Run&#34上有一个例外; :

System.InvalidOperationException : Targettype button does not correspond to Control Element

Stacktrace : System.Windows.Style.CheckTargetType(Object element)

即使没有任何字段(只是文本块),我的所有Windows / UC都会出现此错误

我根本不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

我在模态对话框中遇到了类似的错误。为了调试,我在对话框中添加了一个PreviewLostKeyboardFocus事件处理程序。检查KeyboardFocusChangedEventArgs NewFocus属性告诉我焦点更改在哪个控件上遇到问题。

对我来说,当从关闭按钮切换到对话框中的TabItem时会发生这种情况。为了解决这个问题,我设置了KeyboardNavigation.IsTabStop =&#34; false&#34;在TabItem上,以便在更改焦点时按Tab键会忽略TabItem。我的TabItem看起来像这样:

<TabItem Name="MyTab" Header="Test Header" VerticalContentAlignment="Stretch"
 VerticalAlignment="Stretch" Height="Auto" KeyboardNavigation.IsTabStop="False">

这可能是一个更好的解决方案,但这可以防止异常。