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

PowerShell中WPF数据绑定至对象子属性的问题

解决PowerShell中WPF DataGrid绑定ObservableCollection子属性的问题

你的问题核心是混淆了ItemsSource绑定目标和子属性显示逻辑:ItemsSource需要绑定到整个ObservableCollection集合,而子属性的读取/写入应该通过DataGrid的列绑定来配置,不能直接在ItemsSource的路径里指定子属性。

修正步骤:

  • 第一步:将ItemsSource的绑定路径改回[Grid1],指向你的ObservableCollection对象
  • 第二步:为DataGrid手动定义列,分别绑定到子属性SubObject.ItemName和SubObject.ItemCount,确保双向绑定生效

修正后的完整代码:

$HashDataContexts = @{}
$FormMain.DataContext = $HashDataContexts

$DGSourceData = @()
$SourceData = @(@("Item One", 1), @("Item Two", 2), @("Item Three", 3))
foreach($SourceItem in $SourceData) {
    $SourceObject = [PSCustomObject]@{
        SubObject = [PSCustomObject]@{
            ItemName = $SourceItem[0]
            ItemCount = $SourceItem[1]
        }
    }
    $DGSourceData += $SourceObject
}
$DataContext = New-Object -TypeName System.Collections.ObjectModel.ObservableCollection[Object] -ArgumentList (,$DGSourceData)
$HashDataContexts.Add("Grid1",$DataContext)

# 修正ItemsSource绑定,指向整个集合
$DGBinding = New-Object System.Windows.Data.Binding
$DGBinding.Path = "[Grid1]"
$DGBinding.Mode = [System.Windows.Data.BindingMode]::TwoWay
[System.Windows.Data.BindingOperations]::SetBinding($DG1,[System.Windows.Controls.DataGrid]::ItemsSourceProperty, $DGBinding)

# 手动创建DataGrid列,绑定子属性
$colName = New-Object System.Windows.Controls.DataGridTextColumn
$colName.Header = "Item Name"
$nameBinding = New-Object System.Windows.Data.Binding
$nameBinding.Path = "SubObject.ItemName"
$nameBinding.Mode = [System.Windows.Data.BindingMode]::TwoWay
$colName.Binding = $nameBinding

$colCount = New-Object System.Windows.Controls.DataGridTextColumn
$colCount.Header = "Item Count"
$countBinding = New-Object System.Windows.Data.Binding
$countBinding.Path = "SubObject.ItemCount"
$countBinding.Mode = [System.Windows.Data.BindingMode]::TwoWay
$colCount.Binding = $countBinding

# 将列添加到DataGrid
$DG1.Columns.Add($colName)
$DG1.Columns.Add($colCount)

# Show the window
$FormMain.Dispatcher.InvokeAsync{$FormMain.ShowDialog()}.Wait()

关键说明:

  • WPF的ItemsSource要求绑定的是集合对象,而不是集合中元素的某个属性,你原来的[Grid1.SubObject]写法不符合绑定规则,导致无法正确解析。
  • 当集合中的元素是嵌套对象时,需要为DataGrid的每一列单独配置绑定路径,明确指向子属性,这样才能实现双向绑定——修改DataGrid单元格的值时,会同步更新到SubObject的对应属性中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:40:40