Powershell wpf datagrid

Powershell WPF DataGrid

The WPF DataGrid is a powerful control for displaying and editing data in a tabular format in a Windows Presentation Foundation (WPF) application.

Here is an example of how to create and use a DataGrid in Powershell with WPF:


Add-Type -AssemblyName PresentationFramework

# Create WPF window
$window = New-Object System.Windows.Window
$window.Title = "DataGrid Example"
$window.Width = 400
$window.Height = 300

# Create DataGrid
$dataGrid = New-Object System.Windows.Controls.DataGrid
$dataGrid.AutoGenerateColumns = $false

# Create columns for DataGrid
$column1 = New-Object System.Windows.Controls.DataGridTextColumn
$column1.Header = "Name"
$column1.Binding = New-Object System.Windows.Data.Binding "Name"

$column2 = New-Object System.Windows.Controls.DataGridTextColumn
$column2.Header = "Age"
$column2.Binding = New-Object System.Windows.Data.Binding "Age"

# Add columns to DataGrid
$dataGrid.Columns.Add($column1)
$dataGrid.Columns.Add($column2)

# Create data
$person1 = [PSCustomObject]@{
    Name = "John"
    Age = 25
}

$person2 = [PSCustomObject]@{
    Name = "Mary"
    Age = 30
}

# Create collection for DataGrid
$collection = New-Object System.Collections.ObjectModel.ObservableCollection[Object]
$collection.Add($person1)
$collection.Add($person2)

# Set collection as DataGrid's item source
$dataGrid.ItemsSource = $collection

# Add DataGrid to window
$window.Content = $dataGrid

# Show the window
$window.ShowDialog()
  

In this example, we first create a WPF window using the System.Windows.Window class. Then, we create a DataGrid using the System.Windows.Controls.DataGrid class. We set the AutoGenerateColumns property to $false to manually define the columns for the DataGrid.

Next, we create two DataGridTextColumn objects, each representing a column in the DataGrid. We set the Header property to the column’s header text and the Binding property to specify the data field to bind to. In this case, we use the “Name” and “Age” properties of the data objects.

We then create some data objects using [PSCustomObject] and add them to an ObservableCollection, which will serve as the DataGrid’s item source. Finally, we set the DataGrid’s item source to the ObservableCollection, and add the DataGrid to the window’s content. The window is displayed using the ShowDialog() method.

Leave a comment