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

WPF PowerShell获取ListView及内嵌GridView选中项值的方法

PowerShell WPF ListView选中项获取方案

问题场景

开发基于PowerShell的Windows应用,拉取当前AD站点内的网络打印机,通过内嵌GridView的ListView控件展示打印机多列属性,供用户选择后执行安装。当前已完成控件定义和数据填充逻辑,需要实现选中项提取、传入打印机连接函数的功能。

现有实现代码

ListView控件XAML定义

<ListView Name="Impresoras" Margin="5" Grid.Row="0">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Laser" DisplayMemberBinding="{Binding PrinterName}" />
            <GridViewColumn Header="Driver" DisplayMemberBinding="{Binding DriverName}"/>
            <GridViewColumn Header="Ubicacion" DisplayMemberBinding="{Binding Location}"/>
            <GridViewColumn Header="IP" DisplayMemberBinding="{Binding PortName}"/>
            <GridViewColumn Header="Servidor" DisplayMemberBinding="{Binding ServerName}"/>
        </GridView>
    </ListView.View>
</ListView>

数据填充PowerShell逻辑

$tablaImpresoras = Get-ADObject -LDAPFilter "(objectCategory=printQueue)" -Properties PrinterName, DriverName, Location, PortName, ServerName | Select-Object -Property PrinterName, DriverName, Location, @{Name='PortName';Expression={$_.PortName}}, ServerName
$var_Impresoras.ItemsSource = $tablaImpresoras

实现方法

WPF ListView的选中项不需要从内嵌GridView的单元格中提取,直接读取控件自带的选中属性即可,返回值就是绑定到ItemsSource的原始打印机对象,自带所有绑定的属性字段。

  • 单选模式(默认)
    直接访问SelectedItem属性即可获取单个选中的打印机对象,建议加非空判断避免用户未选中时报错:
    # 示例:写在安装按钮的点击事件中
    $installButton.Add_Click({
        # 提取选中项存入变量
        $selectedPrinter = $var_Impresoras.SelectedItem
        
        # 未选中打印机时弹出提示
        if (-not $selectedPrinter) {
            [System.Windows.MessageBox]::Show("请先选择需要安装的目标打印机")
            return
        }
        
        # 直接传入连接打印机的函数即可,可通过属性访问所需字段
        # 示例:$selectedPrinter.PrinterName 获取打印机名,$selectedPrinter.PortName 获取端口地址
        Add-NetworkPrinter -InputObject $selectedPrinter
    })
    
  • 多选模式
    如果需要支持用户按住Ctrl/Shift多选打印机,先在XAML的ListView标签中添加属性SelectionMode="Extended",再通过SelectedItems属性获取选中项集合,遍历执行安装即可:
    $installButton.Add_Click({
        $selectedPrinterList = $var_Impresoras.SelectedItems
        if ($selectedPrinterList.Count -eq 0) {
            [System.Windows.MessageBox]::Show("请先选择需要安装的目标打印机")
            return
        }
        foreach ($printer in $selectedPrinterList) {
            Add-NetworkPrinter -InputObject $printer
        }
    })
    

优化提示

现有数据填充逻辑中PortName字段的计算属性写法冗余,可直接简化,不影响数据绑定结果:

# 简化后的数据查询逻辑
$tablaImpresoras = Get-ADObject -LDAPFilter "(objectCategory=printQueue)" -Properties PrinterName, DriverName, Location, PortName, ServerName | Select-Object -Property PrinterName, DriverName, Location, PortName, ServerName

内容的提问来源于stack exchange,提问作者Franco Canciani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:54:28