Reputation: 3481
I am trying to get a handler added to a form/wpf button by Add_Click. I do not know the function name beforehand, so constructing the function name is important. Then passing it to Add_Click.
Trying the following, I get
$num = 1
function somefn1 () {}
$fn = $Function:"somefn$num"
$somebutton.Add_Click($fn)
The error is
Cannot convert argument "value", with value: "somefn1", for "add_Click" to type "System.Windows.RoutedEventHandler": "Cannot convert the
"somefn1" value of type "System.String" to type "System.Windows.RoutedEventHandler"."
At xyz
+ ... $somebutton.Add_Click("somefn$num") }
+ ~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
I am not sure, how to get around that. Any ideas or hints?
Upvotes: 0
Views: 153
Reputation: 3481
Working: using a string to attach an existing function (mind the scope of the handler)
$elName = "theButton" # => Name="theButton"
$fnName = "mynamespace." + "function_name"
$fns = Get-ChildItem function: | Where-Object { $_.Name -like $fnName }
$Form.FindName($elName).Add_Click( $fns[0].ScriptBlock )
function mynamespace.function_name($Sender, $EventArgs) {
Write-Host "works !"
}
Upvotes: 1