模拟datagrid标题列上的单击

时间:2014-04-01 17:55:39

标签: c# wpf silverlight datagrid

我一直在寻找并找到:How to simulate the user click on a column header of a datagrid in WPF?,但我不知道我必须放入什么" your_control",我使用的是Silverlight 5,有人可以提供帮助我吗?

DataGridColumnHeaderItemAutomationPeer peer = new DataGridColumnHeaderItemAutomationPeer (Your_control);

我的DataGrid是dgEmployee

当我尝试使用它时,定义它:

DataGridColumnHeaderItemAutomationPeer peer = new DataGridColumnHeaderItemAutomationPeer (dgEmployee);

系统发给我一个错误:

"最好的重载方法匹配' System.Windows.Automation.Peers.DataGridColumnHeaderAutomationPeer.DataGridColu mnHeaderAutomationPeer(System.Windows.Controls.Primitives.DataGridColumnHeader)'有一些无效的论据"

如何将dgEmployee的DataGridColumnHeader作为参数?

谢谢!

1 个答案:

答案 0 :(得分:1)

解决方案是:

System.Windows.Controls.Primitives.DataGridColumnHeader headerObj;

headerObj = GetColumnHeaderFromColumn(myDataGrid, myDataGrid.Columns[1].Header);

System.Windows.Automation.Peers.DataGridColumnHeaderAutomationPeer peer =
                                new DataGridColumnHeaderAutomationPeer(headerObj);
                            IInvokeProvider invoker = (IInvokeProvider)peer;
                            invoker.Invoke(); // Invoke a click programmatically   


    private System.Windows.Controls.Primitives.DataGridColumnHeader GetColumnHeaderFromColumn(DependencyObject parent, object header)
    {            
        int count = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < count; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (child != null)
            {
                if (child is System.Windows.Controls.Primitives.DataGridColumnHeader)
                {
                    System.Windows.Controls.Primitives.DataGridColumnHeader columnHeader = child as System.Windows.Controls.Primitives.DataGridColumnHeader;
                    if (header.Equals(columnHeader.Content))
                    {
                        return columnHeader;
                    }
                }
                else
                {
                    System.Windows.Controls.Primitives.DataGridColumnHeader columnHeader = GetColumnHeaderFromColumn(child, header);
                    if (null != columnHeader)
                    {
                        return columnHeader;
                    }
                }
            }
        }

        return null;

    }

也许对某人有帮助,来自墨西哥的问候

相关问题