1
votes

I'm trying to put a data grid in a WPF. Simple enough in Powershell.. But when i run the code in Powershell 2.0, it can't find gives me errors.

Sample code:

Add-Type -AssemblyName PresentationFramework

$xaml = [xml] @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="My window" Height="300" Width="300">
<DockPanel>
    <Button x:Name="okButton" Content="OK" DockPanel.Dock="Bottom" />
    <DataGrid x:Name="DataGrid" DockPanel.Dock="Top"/>
</DockPanel>
</Window>
"@

$reader = New-Object System.Xml.XmlNodeReader $xaml
$form = [Windows.Markup.XamlReader]::Load($reader)

$okButton = $form.FindName("okButton")

$okButton.add_Click({ $form.Close() })

$form.WindowStartupLocation = "CenterScreen"
$form.ShowDialog();

If you remove this line, everything work fine:

<DataGrid x:Name="DataGrid" DockPanel.Dock="Top"/>

Anyone has any suggestions?

Error i get in Powershell 2.0:

Exception calling "Load" with "1" argument(s): "The tag 'DataGrid' does not exist in XML namespace 'http://schemas.microsoft.com/winfx /2006/xaml/presentation'. Line '0' Position '0'." At line:15 char:42 + $form = [Windows.Markup.XamlReader]::Load <<<< ($reader) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

1
What exact errors do you receive? 2 possible options from top of my head: different .net version, or additional references load required, or both.Mike Makarov
See the updated question with the error..Marc Kellerman
Works fine in PS 4.0, .NET 4.5. What version of .NET do you have?Jan Chrbolka
I know it does.. The question asks why doesn't it work in PS 2.0.. I have an environment that is PS 2.0 only.. :/Marc Kellerman
No need to get all excited ;) All I was trying to say was, that the error seems specific to version 2 of PowerShell. I can also confirm that version of .NET does not mater.Jan Chrbolka

1 Answers

0
votes

By default PowerShell 2.0 will use .NET framework 2.0. There is no DataGrid in .NET v 2.0. Type :

[environment]::Version

If you get this, or something else starting with 2...

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      50727  7905

Your PowerShell session is using NET 2.0. How to "Enable .Net 4.0 access from PowerShell V2"?

EDIT:

To fix this on PS 2.0 ....

Create files C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.config and C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe.config with the following content:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <startup useLegacyV2RuntimeActivationPolicy="true"> 
        <supportedRuntime version="v4.0" />    
    </startup> 
</configuration>

After this, you can load .NET 4 run-times:

Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF\PresentationFramework.dll"

assuming you have .NET 4 loaded.