Handling Button Clicks in WPF with PowerShell
May 21, 2009 at 12:05 PM
—
Andy Schneider
In my last post, I discussed how to fire up a WPF window in PowerShell. You can make XAML look pretty amazing, but if buttons and controls never get wired up to any functionality, it gets boring pretty quick. Here is the code I had last time with a small addition.Blend allows you to name your controls. This turns into what you see in line 018 in the XAML. x:Name=”Close.”
| 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027
| [xml]$xaml = @" <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="Window" Title="Blend and PowerShell" Width="640" Height="480" AllowsTransparency="False"> <Grid x:Name="LayoutRoot"> <Rectangle Margin="22,8,22,0" VerticalAlignment="Top" Height="178" Stroke="#FF000000"> <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF000000" Offset="0"/> <GradientStop Color="#FF861A1A" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> <Button Margin="121,0,129,96" VerticalAlignment="Bottom" Height="100" Content="Button" x:Name="Close"/> </Grid> </Window> "@ $reader = New-Object System.Xml.XmlNodeReader $xaml $d = [Windows.Markup.XamlReader]::Load($reader) $d.FindName("Close").add_click({ $d.Close() }) $d.ShowDialog() | out-null |
Once you have the name, you can call the FindName method (see line 024) on your WPF Window. This allows you to find the named control that you want to add event handling for. Using FindName, we can add the add_Click method and pass in the ScriptBlock that we want to execute on the click event.
When you run this, clicking the button will close the dialog box.
4fdfa5f3-1fcc-41a8-a15d-793eeb4629f2|0|.0
Posted in:
Tags: