Reputation: 111
I'm not a professional developer, and JUST started with WPF, so be gentle if I'm doing something stupid in this code. My previous sole experience with GUI is Microsoft Access VBA. So I'm familiar with the basic idea of controls and events and event handlers. But WPF is a bit different. And doing it in PowerShell.
I found these two other posts about doing this in C#, so my question is, what is the equivalent of doing this in PowerShell? (I'm not even sure the 2nd post is WPF, but the answers seem similar to the first post in simply using control.event += eventhandler)
adding event handlers on dynamically created WPF controls
Event Handler for a dynamically created control
I've got event handlers working in general using the $varname.Add_event({}) syntax. So basic event handling for static controls defined in the XAML isn't an issue.
This code is simplified, but it should illustrate the question. I'm dynamically creating a series of buttons in code:
for ($i = 1; $i -le 5; $i++) {
$Btn = New-Object System.Windows.Controls.Button
$Btn.Name = "btn$i"
$Btn.Content = "Hello World $i"
$Btn.HorizontalAlignment = "Left"
$Btn.VerticalAlignment = "Center"
$Btn.Margin = "10,$($i*50),0,0"
$Btn.FontWeight = "Bold"
$WPFgrdMyGrid.Children.Add($Btn) | Out-Null
}
This works all well and good. Visually, the buttons appear on screen and look correct.
But now, how do I add an event handler on each button?
Taking a clue from the other posts I linked to above I tried
$Btn.Add_Click = ({my handler code})
but I get the following error:
Exception setting "Add_Click": "Cannot set the Value property for PSMemberInfo object of type
"System.Management.Automation.PSMethod"."
Upvotes: 1
Views: 978
Reputation: 111
Well, now I just feel silly. Finally figured it out. I's no different than having an XAML pre-defined control...
$Btn.Add_Click({my handler code})
Upvotes: 3