August 27, 2009

Powershell and XAML

Someone asked me if you can load up xaml in powershell. My response was "What can't powershell do!". The only thing is that you must start powershell using a single-threaded apartment like:
powershell -sta -file MyXAML.ps1
Here is one way of doing it with the xaml file not directly in the powershell script:
Add-Type -AssemblyName PresentationFramework
[System.Reflection.Assembly]::LoadFrom(".\lib\WPFToolkit.dll")
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

function LoadXaml
{
param($fileName)

[xml]$xaml = [IO.File]::ReadAllText($fileName)
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
[Windows.Markup.XamlReader]::Load( $reader )
}

# Load XAML
$app = new-object System.Windows.Application
$form = LoadXaml('.\dialog.xaml')
Your dialog.xaml file can look like:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
>
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>

No comments:

Post a Comment