Cyndy
Cyndy

Reputation: 93

Simulate a click on datagrid header column

I was looking for and found: How to simulate the user click on a column header of a datagrid in WPF?, but I don't know what I must put in "your_control", I'm using Silverlight 5, can somebody help me??

DataGridColumnHeaderItemAutomationPeer peer = new DataGridColumnHeaderItemAutomationPeer (Your_control);

my DataGrid is dgEmployee

When I try use it, defining it so:

DataGridColumnHeaderItemAutomationPeer peer = new DataGridColumnHeaderItemAutomationPeer (dgEmployee);

System send me an error:

"The best overloaded method match for 'System.Windows.Automation.Peers.DataGridColumnHeaderAutomationPeer.DataGridColu‌​mnHeaderAutomationPeer(System.Windows.Controls.Primitives.DataGridColumnHeader)' has some invalid arguments"

How I can put the DataGridColumnHeader of my dgEmployee as argument?

Thanks!!

Upvotes: 2

Views: 1131

Answers (1)

Cyndy
Cyndy

Reputation: 93

the solution is:

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;

    }

maybe can be helpful for somebody, regards from Mexico

Upvotes: 1

Related Questions