0

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

1 回答 1

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}" />
于 2012-04-13T09:38:47.187 回答