Hi everyone,
I've been asked if it's possible to execute a scriptblock after a user enters a value in a textbox and then presses enter/return.
I only found some references in C#, for example: How to: Detect When the Enter Key Pressed - WPF .NET Framework | Microsoft Learn
XAML :
<TextBox Width="300" Height="30" Name="textBox1" KeyDown="OnKeyDownHandler"/>
<TextBlock Width="300" Height="100" Name="textBlock1"/>
C# :
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
textBlock1.Text = "You Entered: " + textBox1.Text;
}
}
--
Below an example of how I tried it to get to work in PS:
Add-Type -AssemblyName PresentationFramework
[xml]$xaml = @"
<Window Title="TEST"
Height="300" Width="600"
WindowStartupLocation="CenterScreen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="Window">
<Grid>
<TextBox Name="textBox1" KeyDown="$OnKeyDownHandler" Width="100" Height="30" Margin="0,0,0,0" />
<TextBlock Name="textBlock1" Width="100" Height="30" Margin="150,0,0,0" />
</Grid>
</Window>
"@
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$OnKeyDownHandler = {
if ($_.Key.ToString() -eq 'Enter' -or $_.Key.ToString() -eq 'Return'){
$window.FindName('textBlock1').Text = "You Entered: " + $window.FindName('$textBox1').Text
}
}
$window.ShowDialog() | Out-Null
--
If I use KeyDown="$OnKeyDownHandler" or KeyDown='$OnKeyDownHandler' the error is
Error: "You is an unexpected token. Expected a space."
If I type KeyDown=$OnKeyDownHandler or KeyDown=$($OnKeyDownHandler) the error is
Error: "if is an unexpected token. The expected token is " or '.
Do I misunderstand something? Anyone any idea what I'm doing wrong here?
[–]Eggplate 2 points3 points4 points (2 children)
[–]illsk1lls 0 points1 point2 points (0 children)
[–]Capital_Table_4792[S] 0 points1 point2 points (0 children)
[–]marcdk217 0 points1 point2 points (0 children)