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

WPF C# DataGrid使用RowDetailsTemplate嵌套DataGrid绑定异常求助

问题分析与解决

错误原因

错误提示明确说明:RowDetailsTemplate内部的DataContext是当前选中的DataRowView(即主DataGrid的单行数据对象),而非你原本绑定的ViewModel,因此找不到CurrentTable属性。

解决方案

通过以下两种方式,让子DataGrid的绑定指向主DataGrid的DataContext(即你的ViewModel)即可解决问题:

方法1:使用RelativeSource绑定父级DataGrid

<DataGrid Name="dataGrid" ItemsSource="{Binding Path=CurrentTable.DefaultView, IsAsync=False}"
          AutoGenerateColumns="True" 
          AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"
          SelectedItem="{Binding SelectedItem}">
    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <DataGrid ItemsSource="{Binding Path=DataContext.CurrentTable.DefaultView, 
                              RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, 
                              IsAsync=False}"/>
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
</DataGrid>

方法2:使用ElementName绑定主DataGrid

<DataGrid Name="dataGrid" ItemsSource="{Binding Path=CurrentTable.DefaultView, IsAsync=False}"
          AutoGenerateColumns="True" 
          AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"
          SelectedItem="{Binding SelectedItem}">
    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <DataGrid ItemsSource="{Binding Path=DataContext.CurrentTable.DefaultView, 
                              ElementName=dataGrid, 
                              IsAsync=False}"/>
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
</DataGrid>

说明

两种方案本质都是让子DataGrid的绑定源回到主DataGrid的DataContext,这样就能正确访问到CurrentTable.DefaultView属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:52:17