wpf - 复选框失去焦点与 FocusManager.IsFocusScope ="True"

标签 wpf checkbox focus

我看到我的 CheckBox 出现奇怪的行为及其焦点/选项卡顺序。

首先是一些“工作”代码:

<Grid>    
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Button Grid.Row="0" Width="100" Height="25"/>
    <TabControl Grid.Row="1" >
        <!--TabItem Header="tabItem1" Name="tabItem1"-->
        <TabItem Header="tabItem1" Name="tabItem1" FocusManager.IsFocusScope="True">
            <ScrollViewer>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>

                    <TextBox Grid.Row="0" />
                    <TextBox Grid.Row="1"/>
                    <CheckBox Grid.Row="2" Content="Test"  />
                    <TextBox Grid.Row="3"/>
                </Grid>
            </ScrollViewer>
        </TabItem>
    </TabControl>
</Grid>

如果您尝试此操作,则 Tab 键顺序可以正常工作 - 只要您不选中 CheckBox。如果我选中 CheckBox 它会失去焦点,并且下一个 Tab 按下会将焦点设置为 Button。

如果我删除 FocusManager.IsFocusScope="True"一切正常。

我的问题是这种行为是想要的还是错误的?

最佳答案

这种行为在某种程度上是预料之中的。为了修复它,您可以在窗口上为 GotFocus 添加一个处理程序。

假设您的复选框名为 chkBox,如下所示:

protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
    base.OnGotKeyboardFocus(e);

     if (e.Source == chkBox)
         FocusManager.SetFocusedElement(this, chkBox); 

}

这个问题和一些类似的问题在 this msdn thread 中有更详细的讨论。 .

关于wpf - 复选框失去焦点与 FocusManager.IsFocusScope ="True",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14275235/

相关文章:

Firefox 光标不可见,单击其他任何内容时变为可见

swift - 如何处理 tvOS Remote 中的菜单按钮操作

.net - 如何将简单的 .net 属性绑定(bind)到标签并使其自动更新

c# - 使用 XAML 中的通用 IValueConverter

javascript - 未提供过滤器时 Angular 显示全部

javascript - 未隐藏复选框选项

android - 如何去掉 CheckBox 右边不需要的空格?

javascript - Vue.js 将值显示为价格,但将其保留为 int

C# TreeView 并绑定(bind)到数据库

c# - 将 Directx12 资源移植到 XAML 元素:关于 WRL::ComPtr 替换的建议?