PowerShell中无法将对象集合绑定到ListBox问题求助
解决PowerShell WPF ListBox绑定无内容的问题
你的代码存在几个关键错误,导致ListBox无法正确显示数据,以下是修正点和完整代码:
错误分析
- 集合生成逻辑错误:原代码中
ForEach-Object每次返回累加的$out数组,导致$dgSourceData变成嵌套数组结构,而非单一的对象集合。 - 绑定属性匹配错误:绑定目标是ListBox,但你用了
[DataGrid]::ItemsSourceProperty,应该对应[ListBox]::ItemsSourceProperty。 - 无效的属性引用:
$dgSourceData.SubObject不存在,$dgSourceData本身就是对象数组,直接转换为ObservableCollection即可。 - 控件查找变量错误:按钮查找时误用未定义的
$window变量,需改用正确的窗口对象$FormMain。
修正后的完整代码
using namespace System.Windows using namespace System.Windows.Data using namespace System.Windows.Controls using namespace System.Windows.Markup using namespace System.Xml using namespace System.Collections.ObjectCollection Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase # 模拟用户列表 $liste = "Marie","Michel","Jean","Adam","Paul" # 正确生成对象集合 $dgSourceData = $Liste | ForEach-Object { [PSCustomObject]@{ Name = $_ } } [xml]$xaml = @" <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:SetTelephone" Title="MainWindow" Height="365" Width="837" > <Grid> <Label x:Name="LabelCompte" Content="Compte :" HorizontalAlignment="Left" Margin="122,128,0,0" VerticalAlignment="Top" Width="123" Height="31" FontSize="18" FontFamily="Arial"/> <Label x:Name="LabelTel" Content="Tel :" HorizontalAlignment="Left" Margin="453,128,0,0" VerticalAlignment="Top" FontFamily="Arial" FontSize="18" Width="80" Height="31"/> <TextBox x:Name="BoxTel" HorizontalAlignment="Left" Margin="552,128,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="139" FontFamily="Arial" FontSize="18" Height="31"/> <Button x:Name="BoutonMaj" Content="Maj" HorizontalAlignment="Left" Margin="376,255,0,0" VerticalAlignment="Top" Height="45" Width="100"/> <Button x:Name="BoutonLire" Content="Lire" HorizontalAlignment="Left" Margin="603,255,0,0" VerticalAlignment="Top" Height="43" Width="106"/> <ListBox x:Name="ListBox" Margin="215,127,389,162" FontFamily="Arial" FontSize="18"/> </Grid> </Window> "@ $FormMain = [XamlReader]::Load([XmlNodeReader] $xaml) # 设置DataContext为包含集合的哈希表 $FormMain.DataContext = @{ GridDataSource = [ObservableCollection[Object]]$dgSourceData } # 创建绑定,使用ListBox的ItemsSourceProperty $dgBinding = [Binding]@{ Mode = [BindingMode]::TwoWay Path = '[GridDataSource]' } $null = [BindingOperations]::SetBinding( $FormMain.FindName('ListBox'), [ListBox]::ItemsSourceProperty, $dgBinding ) # 正确查找按钮控件 $Maj = $FormMain.FindName('BoutonMaj') $Lire = $FormMain.FindName('BoutonLire') $null = $FormMain.ShowDialog()
补充说明
如果需要让ListBox显示对象的Name属性文本,可以在XAML的ListBox里添加DisplayMemberPath属性:
<ListBox x:Name="ListBox" Margin="215,127,389,162" FontFamily="Arial" FontSize="18" DisplayMemberPath="Name"/>
内容的提问来源于stack exchange,提问作者MichelM
相关产品推荐
相关产品推荐

