You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell类方法的脚本块中访问类实例?

PowerShell类中WPF事件脚本块访问实例属性的解决方法

你的问题出在WPF按钮的Add_Click脚本块作用域上:脚本块内部的$this并不指向你的Window类实例,而是脚本块自身的上下文(通常为空或非预期对象),所以会触发空引用异常。

解决思路是在注册事件前,将类实例的引用捕获到一个局部变量中,让脚本块通过闭包访问这个变量。修正后的代码如下:

Add-Type -AssemblyName PresentationFramework
class Window 
{
    [System.Windows.Window]$window
    [System.Windows.Controls.Button]$button
    [int]$count = 0

    Window()
    {
        [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="C#Shell!">
            <Grid x:Name="Grid">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="100"/>
                </Grid.RowDefinitions>
                
                <ListView x:Name="List" />
                <Button x:Name="AddButton" Content="Add" Grid.Row="1"/>
            </Grid>
        </Window>
"@
        $reader = [System.Xml.XmlNodeReader]::new($xaml)
        $this.window = [System.Windows.Markup.XamlReader]::Load($reader)
        $this.button = $this.window.FindName("AddButton")
        
        # 捕获类实例引用到局部变量
        $self = $this
        $this.button.Add_Click({
            # 使用$self访问类实例的属性
            $self.window.FindName("List").Items.Add("Item" + ($self.count++).ToString())
        })
        $this.window.ShowDialog()
    }
}

$window = [Window]::new()

关键说明

  • 在注册点击事件前,将$this赋值给$self变量,脚本块会通过闭包保留这个变量的引用
  • 脚本块内部使用$self替代$this,就能正确访问到Window类实例的window和count属性

内容的提问来源于stack exchange,提问作者sz ppeter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:25:16