将嵌套对象绑定到 WPF 数据网格

Bind nested object to WPF data grid

我有一个包含两列(A 和 B)的 DataGrid。每个列单元格都包含一个组合框控件。

我有一个包含两个列表项的对象,我想将它们绑定到网格视图,但绑定不起作用。

两个数据模板中的绑定工作不正常。 UI 显示命名空间而不是值。

示例项目: https://1drv.ms/u/s!Ah27QQNpKj4jj2xsIsQamaOXOlin?e=jNAj2H

ViewModel

public class MainWindowViewModel {
  public List < MainObject > MainObjects { get; set; }

  public MainWindowViewModel() {
    MainObjects = new List < MainObject > {
      new MainObject {
        AColumns = new List < ColumnA > {
          new ColumnA { Name = "A1" },
          new ColumnA { Name = "A1" }
        },
        BColumns = new List < ColumnB > {
          new ColumnB { Name = "B1" },
          new ColumnB { Name = "B1" }
        },
      }
    };
  }
}

public class MainObject {
  public List < ColumnA > ?AColumns { get; set; }
  public List < ColumnB > ?BColumns { get; set; }
}

public class ColumnA {
  public string ? Name { get; set; }
}

查看:

<Window x:Class="TestDataGrid.MainWindow"
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <DataGrid ItemsSource="{Binding MainObjects}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Column A" Width="Auto">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock HorizontalAlignment="Center">
                            <TextBlock.Text>
                                <PriorityBinding>
                                    <Binding Path="Name" Mode="TwoWay" />
                                </PriorityBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox IsEditable="True" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding AColumns}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Window>

您必须使用“DisplayMemberPath”属性 而不是“Text”属性。像这样

 <ComboBox IsEditable="True" ItemsSource="{Binding AColumns}" SelectedValuePath="Name" DisplayMemberPath="Name"/>