开发者

In WPF, how do I bind in the DataGrid.RowDetailsTemplate?

开发者 https://www.devze.com 2023-02-18 07:19 出处:网络
I have a DataGrid which is bound to an ObservableCollection of a custom class.Thecollection is a property in a ViewModel, and the grid works fine, including with changes to the collection.

I have a DataGrid which is bound to an ObservableCollection of a custom class. The collection is a property in a ViewModel, and the grid works fine, including with changes to the collection.

I want to use the RowDetailsTemplate to display two additional collections in a StackPannel, like so:

        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <StackPanel Name="GrcidSP" Orientation="Horizontal">
                    <DataGrid Name="ClusterIndexGrid" AutoGenerateColumns="True" 
                              ItemsSource="{Binding ClusterIndexColumns}"
                              CanUserAddRows="False" CanUserResizeRows="False"
                              Width="Auto"/>
                    <DataGrid Name="IndexGrid" AutoGenerateColumns="True" 
                              ItemsSource="{Binding IndexColumns}"
                              CanUserAddRows="False" CanUserResizeRows="False"
                              Width="Auto"/>
                </StackPanel>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>

ClusterIndexColumns and IndexColumns, the binding sources of the inner grids, are also collections in the ViewModel.

开发者_运维技巧

Problem is, when i display the rowdetails, the datagrids are empty, i.e. not loaded at all, no columns or rows.

In a bid to understand what is going on, i replaced the inner datagrids with label:

        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <StackPanel Name="GridSP" Orientation="Horizontal">
                    <Label Content="{Binding}" Width="Auto" Background="AliceBlue"/>
                </StackPanel>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>

and did not specify the binding source - {Binding}

The label now displays the name of the custom class which is in the collection that is the source of the outer grid.

So somehow, i need to navigate back to the ViewModel as the data context for the inner grids.

But how, pray tell?


OK, so I solved this by adding the ClusterIndexColumns and IndexColumns collections as properties to the custom class which is the displayed in the main grid. Now, when i click on the row, the rowdetails area is opened and the inner grids are loaded fine.

BTW, the collections are populated when the selected row changes in the main grid, by binding the SelectedIndex property to a property in the ViewModel, using

Mode=OneWayToSource

Hope this helps someone.

0

精彩评论

暂无评论...
验证码 换一张
取 消