【发布时间】:2021-11-22 17:14:15
【问题描述】:
我正在编写一个带有小型 WPF GUI 的 PowerShell 脚本。我的代码被组织在一个从中创建单例的类中。我已经读过事件处理程序脚本块中的 $this 指向事件发送者而不是我的包含类实例。如何从事件处理程序访问我的类实例?
例如
class MyClass {
$form #Reference to the WPF form
[void] StartAction([object] $sender, [System.Windows.RoutedEventArgs] $e) {
...
}
[void] SetupEventHandlers() {
$this.form.FindName("BtnStartAction").add_Click({
param($sender, $e)
# !!!! Does not work, $this is not my class instance but the event sender !!!!
$this.StartAction($sender, $e)
})
}
[void] Run() {
$this.InitWpf() #Initializes the form from a XAML file.
$this.SetupEventHandlers()
...
}
}
$instance = [MyClass]::new()
$instance.Run()
【问题讨论】:
-
您可以尝试在
SetupEventHandlers中创建一个实例,如$instance=$this并在处理程序中使用$instance(add_Click)吗? -
$sender是您在add_click中的课程。StartAction不是事件处理程序,它只是您的类的一个方法。修改StartAction签名并通过强制转换$sender调用事件处理程序中的方法([MyClass]$sender).StartAction()
标签: powershell