New-DataGrid examples

Aug 29, 2011 at 12:42 PM

I am working on something that requires multiple controls embedded in a DataGrid. I have a sample here that I started working on. Of course, there are many things wrong with this code.

New-StackPanel -Orientation Vertical {
    New-DataGrid -Name ServerManager -columns {
        New-DataGridCheckBoxColumn -Header "IsSelected" -Binding {New-Binding -Path "selected"}
        New-DataGridTextColumn -Header "ServerName" -Binding {New-Binding -Path "sname"}
        New-DataGridComboBoxColumn -Header "Action" -itemsSource @("Start","Stop","Sleep")
    }
    New-TextBox -Name ServerName
    New-Button -Name btnConnect -MinHeight 30 -On_Click {
        $dataset = @{"selected"=$true;"sname"=$ServerName.Text;"saction"="Stop"}
        $serverManager.ItemsSource = $dataset
    }
} -Show

Here is an explanation of what I want to do:

1. Take the servername input from textbox.

2. Test-Connection $serverName.

3. Set relevant Action as selected.

4. Add a new row to the DataGrid with the values derived.

The present logic I have is not correct. Probably nowhere near to working. I'd like to know how do you do this? Is using ItemTemplates a better way? or the current approach of using different Columns?

Coordinator
Aug 29, 2011 at 4:19 PM

New-StackPanel -Orientation Vertical {
    New-DataGrid -Name ServerManager -Columns {
        New-DataGridCheckBoxColumn -Header "IsSelected" -Binding {New-Binding -Path "selected"}
        New-DataGridTextColumn -Header "ServerName" -Binding {New-Binding -Path "sname"}
        New-DataGridComboBoxColumn -Header "Action" -SelectedValueBinding { New-Binding -Path "saction" } -ItemsSource @("Start","Stop","Sleep") 
    } -ItemsSource { 
        New-Object System.Collections.ObjectModel.ObservableCollection[PSObject]
    } # -CanUserAddRows:$False ## Uncomment CanUserAddRows to hide the "add" row from the DataGrid
    Grid -Columns *,Auto {
        New-TextBox -Name ServerName
        New-Button "Add" -Name btnConnect -Column 2 -On_Click {
            <# Take Action Here to Test-Connection and Set Relevant Action ... #>
            $item= New-Object PSObject -Prop @{"selected"=$true;"sname"=$ServerName.Text;"saction"="Stop"}
            ## Add the item to the list
            $ServerManager.ItemsSource.Add( $item )
            $ServerName.Clear()
        } -IsDefault ## IsDefault makes it so "Enter" clicks this button...
    }
} -Show

 

That'll work ... ItemTemplates would be more complicated to write, and I'm not very clear on what the benefits are when you're using it with a Datagrid.

Aug 29, 2011 at 6:03 PM

Thanks Joel. This is a good start. I was missing the -ItemsSource with New-Datagrid.

Ravi

Aug 31, 2011 at 4:59 PM

I think it is helpful to note that new-datagrid* come from the wpk module, now showui. 

Coordinator
Sep 1, 2011 at 5:26 AM
Unless you're running on .Net 4, in which case it's a default cmdlet ;-)