WPF 数据网格模板列.我错过了什么吗? [英] WPF DataGridTemplateColumn. Am I missing something?

查看:21
本文介绍了WPF 数据网格模板列.我错过了什么吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

     <data:DataGridTemplateColumn Header="Name">
        <data:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}">
            </DataTemplate>
        </data:DataGridTemplateColumn.CellTemplate> 
        <data:DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Name}">
            </DataTemplate>
        </data:DataGridTemplateColumn.CellEditingTemplate> 
    </data:DataGridTemplateColumn>              

这是模板列的清晰示例,对吗?这有什么问题?所以,事情就是这样 - 当用户通过点击 TAB 键浏览 DataGrid 时,它需要点击 TAB 两次(!)才能在 TextBox 中编辑文本.一旦用户获得列焦点,我的意思是即使他刚开始打字,我如何才能使其可编辑?

It's clear example of Template column, right? What could be wrong with that? So, here is the thing - when a user navigates through DataGrid with hitting TAB-key, it needs to hit the TAB twice(!) to be able to edit text in TextBox. How could I make it editable as soon as the user gets the column focus, I mean even if he just starts typing?

好的.我找到了一种方法 - 进入 Grid.KeyUp() 我把代码放在下面:

Ok. I found a way - into Grid.KeyUp() I put the code below:

 if (Grid.CurrentColumn.Header.ToString() == "UserName")
        {
            if (e.Key != Key.Escape) 
            {
                Grid.BeginEdit();

                // Simply send another TAB press
                if (Keyboard.FocusedElement is Microsoft.Windows.Controls.DataGridCell)
                {
                    var keyEvt = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Tab) { RoutedEvent = Keyboard.KeyDownEvent };
                    InputManager.Current.ProcessInput(keyEvt);
                }
            }
        } 

推荐答案

您面临的问题是 DataGridTemplateColumn 中的控件(例如 TextBox)包含在 DataGridCell 中.默认情况下,DataGridCell 具有制表位功能.因此,必须按 TAB 两次才能获得焦点到 TextBox 控件的原因.解决方案是禁用 DataGridCell 的制表位功能.这可以通过 DataGridCell 的样式来完成.

The issue that you faced is that the control (e.g. TextBox) within the DataGridTemplateColumn is contained within a DataGridCell. By default the DataGridCell has tab-stop functionality. Thus the reason for having to hit TAB twice to get focus to your TextBox control. The solution is to disable the tab-stop functionality for the DataGridCell. This can be done via a style for the DataGridCell.

解决办法如下:

<Style TargetType="{x:Type DataGridCell}">
     <Setter Property="KeyboardNavigation.IsTabStop" Value="False" />
</Style>

这篇关于WPF 数据网格模板列.我错过了什么吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆