DataGrid AutoGenerateColumns fails when ItemSource is collection of PSObjects

Sep 9, 2011 at 4:51 AM

I'm getting very different behaviour on two DataGrids (DG) using AutoGenerateColumns. One DG uses an ItemSource of System.Collections.ObjectModel.ObservableCollection[PSObject] filled with objects created using .Add((New-Object PSObject -Property @{'Selected' = $false;'VisualOrder'=$_[0];'SQLConnectionString' = $_[1];})), and this DG will NOT autogenerate the columns. There is a single empty column (the number of rows matches the number of items in the collection).

[The code snippets here are just that - short little snippets that I hope are sufficient to get the point across]

I have another DG that uses an ItemSource of New-Object Library.SQLConnectionStringCollection populated by .Add((New-Object Library.SQLConnectionString($_.Selected, $_.VisualOrder, $_.Template, ([scriptblock]::Create($_.Replacement)).Invoke()))). These types are defined in C#, compiled to a DLL, and used by the PS script. The C# types are nearly identical to the same PSObjects used by the first DG. This second DG, using the types defined in the DLL, does a great job of autogenerating the columns.

I'm guessing the DLL has the type information for the objects in the collection, so the second DG can infer the kinds of columns to use, and the much more dynamic approach of adding free-form PSobjects to a collection means that the first DG cannot know what properties it will encounter - so it simply puts up a single empty column. 

So, for DataGrids whose ItemSource is a collection that holds PSObjects, the DG columns must be explicitly defined?  

Thanks!

Coordinator
Oct 16, 2011 at 7:01 PM

Yeah, basically.

PSObject in PowerShell 2.0 are not dynamic objects in .Net -- they're just PSCustomObject which has no properties at all. Therefore, .Net (and WPF, specifically) won't detect the "properties" that are added to them (they only exist in ETS, as far as .Net is concerned, PSObjects don't have any properties).  I believe we won't have that problem in PS3, where PowerShell is a DLR language, and the PSObject implementation is based on dynamic objects which implement the appropriate interfaces ;-)