Wpf datagrid输入键移动下一行

时间:2015-10-22 23:26:23

标签: c# wpf datagrid

我正在尝试使用数据网格开发一个wpf应用程序,我想让用户输入像excel一样的值。

实施例: datagrid有2列,Name和BarCode 用户正在编辑第一行的BarCode,当用户按Enter键时,焦点应该移动BarCode单元格下面的行。

用户必须能够使用条形码扫描仪在现有产品列表中注册条形码,而无需使用鼠标或键盘。

有关如何实现此行为的任何想法?

谢谢, 弗雷德里科

4 个答案:

答案 0 :(得分:4)

更简单的解决方案是捕获KeyDown事件,如果键是“Enter”,则移至下一个选项卡。

private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
{
    var u = e.OriginalSource as UIElement;
    if (e.Key == Key.Enter && u != null)
    {
        e.Handled = true;
        u.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
    }
}

答案 1 :(得分:2)

我刚用一些额外的代码完成了这个,通过处理Datagrid上的PreviewKeyUp事件,工作代码是:

private void DataGrid_PreviewKeyUp(object sender, KeyEventArgs e)
{
    if ((e.Key == Key.Enter) || (e.Key == Key.Return))
    {
        DataGrid grid = sender as DataGrid;
        if (grid.CurrentColumn.Header.ToString().Equals("Barcode", StringComparison.OrdinalIgnoreCase))
        {
            if (grid.SelectionUnit == DataGridSelectionUnit.Cell || grid.SelectionUnit == DataGridSelectionUnit.CellOrRowHeader)
            {
                var focusedElement = Keyboard.FocusedElement as UIElement;
                focusedElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
             }

             grid.BeginEdit();
             e.Handled = true;
        }
    }
}

保存Barcode属性的列是我唯一需要此行为的列。

答案 2 :(得分:0)

这样的东西?

// MainWindow.xaml.cs

namespace BarcodeImplementationInDG
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        List<Products> lst = new List<Products>();
        public MainWindow()
        {
            InitializeComponent();
            dg.ItemsSource = lst;
        }
    }
    public class Products
    {
        public string Product { get; set; }
        public string Barcode { get; set; }
    }
}

// MainWindow.xaml

<Window x:Class="BarcodeImplementationInDG.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid x:Name="dg" VerticalAlignment="Top" HorizontalAlignment="Left" CanUserAddRows="True" AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding}" Height="309" Width="507" >
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="ProductColumn" Binding="{Binding Product}" Header="Product"  />
                <DataGridTextColumn x:Name="BarcodeColumn" Binding="{Binding Barcode}" Header="Barcode"  />
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

数据将存储在List lst 中,以防您想使用它们

在输入时,焦点自动移动到第二行..

答案 3 :(得分:0)

如果可以接受第三方WPF网格,则可以使用Essential Grid,因为它具有内置于网格中的Excel行为。

如果符合条件,可以通过community license计划免费获得整套控件。注意:我为Syncfusion工作。

相关问题