问题
I need to display 2 datatables when a key value pair item in the list is expanded. And the key value pair item's key should be the expander header. The first table should be bound to the first data grid and second to the second grid. The problem is that the second 'item' on the ItemsControl displays the same value as the first one. (My guess is that the datagrid's ItemsSource binding is incorrect since the VM generates the data for the ListOfKeyValuePairs correctly.)
<!-- Data grid template -->
<DataTemplate x:Key="ValuesTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="data grid header text" Margin="20,0,0,0" Grid.Row="2" />
<DataGrid Grid.Row="0" ItemsSource="{Binding [0]}" />
<DataGrid Grid.Row="1" ItemsSource="{Binding [1]}" />
</Grid>
</DataTemplate>
<!-- List of data tables -->
<ItemsControl ItemsSource="{Binding ListOfKeyValuePairs}" VirtualizingStackPanel.IsVirtualizing="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Expander IsExpanded="True" Margin="0,0,0,10">
<Expander.Header>
<TextBlock Text="{Binding Key}" Margin="0,0,20,0" VerticalAlignment="Top" />
</Expander.Header>
<ContentControl Content="{Binding Value}" ContentTemplate="{StaticResource ValuesTemplate}" ScrollViewer.CanContentScroll="True" Margin="20,0,0,0" />
</Expander>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
回答1:
Your code is working perfectly. But you are using a Grid
inside your ValuesTemplate
. Both items
<DataGrid ItemsSource="{Binding [0]}" />
<DataGrid ItemsSource="{Binding [1]}" />
are on the same position. One DataGrid
is covering the other DataGrid
. Use the defined rows like
<DataGrid Grid.Row="0" ItemsSource="{Binding [0]}" />
<DataGrid Grid.Row="1" ItemsSource="{Binding [1]}" />
or use a simple StackPanel
.
来源:https://stackoverflow.com/questions/40409154/binding-a-listkeyvaluepairstring-listdatatable-items-control-wpf