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

时间:2012-04-13 09:33:20

标签: c# wpf xaml data-binding

我有这件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}" />

为了显示MasterField1?

由于


找到解决方案

我可以这样做:

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

1 个答案:

答案 0 :(得分:0)

为什么不在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}" />