如何以编程方式选择和聚焦DataGrid中的行 [英] How to programmatically select and focus a row in DataGrid

查看:60
本文介绍了如何以编程方式选择和聚焦DataGrid中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。

在我的WPF窗口表单中,我有DataGrid来分散员工列表。当我选择并修改记录时,它将保存在数据库中。我想以编程方式在DataGrid中查找并选择该记录。如果有人会解释如何
这样做,我将不胜感激。

In my WPF window form I have DataGrid to dispalay list of employees. When I selected and modified record it will saved in database. And I would like to programmatically find and select that record in DataGrid. I will appreciate if some will explain how to do that.

谢谢。

推荐答案


大家好。

Hi All.

在我的WPF窗口表单中,我有DataGrid来分散员工列表。当我选择并修改记录时,它将保存在数据库中。我想以编程方式在DataGrid中查找并选择该记录。如果有人会解释如何
这样做,我将不胜感激。

In my WPF window form I have DataGrid to dispalay list of employees. When I selected and modified record it will saved in database. And I would like to programmatically find and select that record in DataGrid. I will appreciate if some will explain how to do that.

谢谢。

嗨    zleug,



您可以尝试以下示例:

Hi   zleug,

You can try the following sample:

        public static void SelectRowByIndex(DataGrid dataGrid, Product pt)
        {
            int rowIndex = 0;
            foreach (object itemch in dataGrid.Items)
            {
                Product pttemp = (Product)itemch;
                if (pt.Id == pttemp.Id)
                {
                    rowIndex = dataGrid.Items.IndexOf(pttemp);
                    break;
                }
            }
            dataGrid.SelectedItems.Clear();
            object item = dataGrid.Items[rowIndex];
            dataGrid.SelectedItem = item;
            DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            SelectRowByIndex(dataGrid, new Product(4, "Product D"));
        }  






这篇关于如何以编程方式选择和聚焦DataGrid中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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