'Powershell set default sorting on datagrid

So i have this wpf datagrid whose columns are defined in a xaml file, i programmatically check data and insert rows in it 1 by 1 after a button is pressed.

I'm trying to understand how i can populate it and set a sorting (the same sorting as i would have clicking on a column header)

in winforms i used to add:

$myDataGrid.Sort($myDataGrid.Columns[3],'Ascending')

after my populating function.

How do i replicate that in WFP (and powershell)?

i did try:

$Datagrid.Items.SortDescription.Add([pscustomobject]@{ColumnName="MyColumn";SortDirection="ListSortDirection.Ascending"})

but i'm having quite some trouble as i only find c# explanations and trying to adapt is not working out....



Solution 1:[1]

Try this:

$sortDescription = New-Object System.ComponentModel.SortDescription('MyColumn', 'Ascending')
$Datagrid.Items.SortDescriptions.Add($sortDescription)

Solution 2:[2]

In C# the solution is this, I hope this can help you to understand how WPF works.

To sort your DataGrid like if you clicked on your column 3, you have to work on DataView created from WPF. In this exampe the DataGrid is sorted every time that columns are AutoGenerated but you can select other event like DataGrid1_Loaded

using System.Windows.Data;

private void DataGrid1_AutoGeneratedColumns(object sender, EventArgs e)
    {
        (((DataGrid)sender).ItemsSource as DataView).Sort = DataGrid1.Columns[3].Header.ToString();
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mm8
Solution 2