如何绑定到 DataGrid RowDetailsTemplate 中的“Master”行

本文关键字:中的 RowDetailsTemplate Master DataGrid 何绑定 绑定 | 更新日期: 2023-09-27 18:30:55

我有这块 XAML

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525"
    x:Name="Window"
    >
    <Grid DataContext="{Binding ElementName=Window}">
    <DataGrid ItemsSource="{Binding Collection}" AutoGenerateColumns="True" CanUserAddRows="False" IsReadOnly="True">
        <DataGrid.RowDetailsTemplate>
            <DataTemplate DataType="{x:Type local:Master}">
                <ListView ItemsSource="{Binding Details}">
                    <ListView.View>
                        <GridView>
                            <GridViewColumn Header="MasterField1"  DisplayMemberBinding="{Binding RelativeSource={????}, Path=MasterField1}" />
                            <GridViewColumn Header="DetailsField1" DisplayMemberBinding="{Binding Field1}"/>
                            <GridViewColumn Header="DetailsField2" DisplayMemberBinding="{Binding Field2}"/>
                        </GridView>
                    </ListView.View>
                </ListView>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>
</Grid>

使用这两个类:

public class Master
{
    public string ID { get; set; }
    public string MasterField1 { get; set; }
    public ObservableCollection<Detail> Details { get; set; }
}
public class Detail
{
    public string MasterID { get; set; }
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

现在我想完成的是 RowDetailsTemplate 中我想显示当前的 MasterField1,但是我应该如何进行绑定才能使其工作?那么我应该怎么做:

<GridViewColumn Header="MasterField1"  DisplayMemberBinding="{Binding RelativeSource={????}, Path=MasterField1}" />

为了显示主场1??

谢谢


找到解决方案

我可以这样做:

<GridViewColumn Header="MasterField1"  DisplayMemberBinding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=DataContext.MasterField1}" />

如何绑定到 DataGrid RowDetailsTemplate 中的“Master”行

为什么不在 Detail 类上创建一个 Master 属性?您也可以在设置 ID 时设置它:

public class Detail
{
    private string _masterID;
    public string MasterID { 
        get {
            return _masterI;
        }
        set {
            _masterID = value;
            Master = FindMasterById(value);
        }
    }
    public Master Master { get ; set ; }
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

然后只需执行绑定:

<GridViewColumn Header="MasterField1"  DisplayMemberBinding="{Binding Path=Master.MasterField1}" />