PowerShell does Xaml

by Doug Finke on May 6, 2008

in PowerShell,WPF,XAML

Jaykul has a nice post on using WPF in PowerShell version 2. Remove xml+site:msdn2.microsoft.com”> from two places in the sample. Looks like his site generates a link to the acronym Xml.

You can inline Xaml with a here string, cast it to an Xml Document and load it with a Xaml Reader. This example shows the new Add-Type cmdlet which does a using on the WPF PresentationFramework assembly.

image

Start the shell using a single-threaded apartment

You must start PowerShell with the new parameter -STA

#requires -version 2

Add-Type -AssemblyName PresentationFramework

[xml] $xaml = @"
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="408">
    <Canvas>
        <Button x:Name='button1'
          Width='75'
          Height='23'
          Canvas.Left='118'
          Canvas.Top='10'
          Content='Click Here' />
    </Canvas>
</Window>
"@

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

$target.ShowDialog() | out-null

{ 1 trackback }

PowerShell WPF from XML Findname Problem | Hardware Infomation and Computer Tutorials
06.29.11 at 6:04 pm

{ 2 comments… read them below or add one }

Niels Grove-Rasmussen 01.15.09 at 3:23 pm

Hi Doug,

Very nice and simple (+) example.

But – How do you equal simple implement functionality on the button?

With Respect
Niels

Doug Finke 01.15.09 at 10:58 pm

Here is one way.
Also checkout
http://huddledmasses.org/powerboots-shoes-for-powershell/
And James Brundages’ posts on WPF
http://blogs.msdn.com/powershell/archive/tags/WPF/default.aspx
—-
Add these lines before the ShowDialog()

$window=$target.FindName(“Window”)

$control=$target.FindName(“button1″)
$eventMethod=$control.”add_click”
$eventMethod.Invoke({$window.Title=”Hello $((Get-Date).ToString(‘G’))”})

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

You are forbidden!