|
$RawXAML = @" |
|
<Window x:Class="WpfApplication3.MainWindow" |
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" |
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" |
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" |
|
xmlns:local="clr-namespace:WpfApplication3" |
|
mc:Ignorable="d" |
|
Title="MainWindow" Height="344.151" Width="232.521" ResizeMode="NoResize"> |
|
<Grid> |
|
<StackPanel x:Name="StackButtonsHere" HorizontalAlignment="Left" Height="231" Margin="22,10,0,0" VerticalAlignment="Top" Width="170"/> |
|
<Button x:Name="AddAButton" Content="The Add-A-Button Button" HorizontalAlignment="Left" Margin="22,277,0,0" VerticalAlignment="Top" Width="170"/> |
|
<TextBox x:Name="ButtonName" HorizontalAlignment="Left" Height="23" Margin="48,249,0,0" TextWrapping="Wrap" Text="Button Name Here" VerticalAlignment="Top" Width="120"/> |
|
</Grid> |
|
</Window> |
|
"@ |
|
|
|
[void][System.Reflection.Assembly]::LoadWithPartialName('PresentationFramework') |
|
[xml]$XAML = $RawXAML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace '^<Win.*', '<Window' |
|
|
|
#Read XAML |
|
$XAMLReader= New-Object System.Xml.XmlNodeReader $XAML |
|
try{ |
|
$Form=[Windows.Markup.XamlReader]::Load($XAMLReader) |
|
} catch { |
|
Throw "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed." |
|
} |
|
|
|
#=========================================================================== |
|
# Load XAML Objects In PowerShell |
|
#=========================================================================== |
|
|
|
$XAML.SelectNodes("//*[@Name]") | |
|
ForEach-Object { |
|
Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name) |
|
} |
|
|
|
#=========================================================================== |
|
# Events |
|
#=========================================================================== |
|
|
|
$WPFAddAButton.Add_Click({ |
|
$NewButton = New-Object System.Windows.Controls.Button |
|
$NewButton.Name = $WPFButtonName.Text |
|
$NewButton.Content = $WPFButtonName.Text |
|
$NewButton.Height = 20 |
|
$WPFStackButtonsHere.AddChild($NewButton) |
|
|
|
# Get the button you just added |
|
$AddedButton = ($WPFStackButtonsHere.Children | |
|
Where-Object { |
|
$_.Name -eq $WPFButtonName.Text |
|
}) |
|
|
|
# Add Click Event |
|
$AddedButton.Add_Click({ |
|
[System.Object]$Sender = $args[0] |
|
$WPFButtonName.Text = $Sender.Name |
|
}) |
|
}) |
|
#=========================================================================== |
|
# Shows the form |
|
#=========================================================================== |
|
$Form.ShowDialog() | Out-Null |