0

I am having problem to bind with an inner DataGrid. The binding works with the DataGrid "Account" but not with "Record". I am using DataGrid.RowDetailsTemplate for the second Datagrid

<Grid>
<Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<DataGrid ItemsSource="{Binding AccountList}" AutoGenerateColumns="False" x:Name="Account">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding AccountNumber}" Header="Account Number" FontSize="16"/>
        <DataGridTextColumn Binding="{Binding Name}" Header="Name" FontSize="16"/>
    </DataGrid.Columns>
    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <DataGrid ItemsSource="{Binding RecordList,Mode=TwoWay}" AutoGenerateColumns="False" x:Name="Record" IsSynchronizedWithCurrentItem="True">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding RecordNumber}" Header="Record Number" FontSize="16"/>
                    <DataGridTextColumn Binding="{Binding Name}" Header="Name" FontSize="16"/>
                </DataGrid.Columns>
            </DataGrid>
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
</DataGrid>

</Grid>

<Grid Grid.Row="1">
    <TextBlock Text="Account Number:"> <TextBox Text="{Binding ElementName=Account, Path=SelectedItem.AccountNumber}" x:Name="ANr"/>
    <TextBlock Text="Record Number:"> <TextBox Text="{Binding ElementName=Record, Path=SelectedItem.RecordNumber}" x:Name="RecordText"/>

</Grid>

The error message:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=Record'. BindingExpression:Path=SelectedItem.RecordNumber; DataItem=null; target element is 'TextBox' (Name='RecordText'); target property is 'Text' (type 'String')

The first TextBox binds without a problem. The second one fails to bind.

Thank you

4

1 回答 1

2

那是因为您的内部DataGrid名称Record仅在您的DataTemplate. 此数据模板将针对每一行重复,因此无法真正按名称绑定到控件。相反,您需要做的是通过SelectedItem外部绑定,DataGrid但为此您需要Account对象中的某些内容来说明已在内部网格中选择了哪一行。所以首先你需要SelectedRecordAccount类中创建,将它绑定到你的内部网格SelectedItem,然后你可以这样做:

<TextBlock Text="Record Number:"> 
<TextBox Text="{Binding ElementName=Account, 
   Path=SelectedItem.SelectedReocrd.RecordNumber}" 
   x:Name="RecordText"/>
于 2013-05-22T11:01:17.697 回答