绑定字典ItemsControl不工作

本文关键字:ItemsControl 工作 DataTable 字典 string 绑定 | 更新日期: 2023-09-27 18:15:57

我需要在展开列表中的字典项时显示字典中的每个数据表(值)。字典项的键应该是扩展头。视图模型正确地填充了数据,但是UI上没有显示任何内容。如何获得要在UI上显示的数据表列表到目前为止,我得到的是:

<!-- Data grid template -->
<DataTemplate x:Key="ValuesTemplate">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock Text="data grid header text" Margin="20,0,0,0" Grid.Row="2"/>
    <DataGrid ItemsSource="{Binding Value[0]}"/>
  </Grid>
</DataTemplate>
<!-- List of data tables -->
<ItemsControl ItemsSource="{Binding myDictionary}" 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}" ContentTemplate="{StaticResource ValuesTemplate}" ScrollViewer.CanContentScroll="True" Margin="20,0,0,0"/>
      </Expander>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

绑定字典<string, DataTable>ItemsControl不工作

在WPF中,ItemsControl.ItemsSource可以绑定到任何实现IEnumerable的类型。那么,Dictionary<TKey, TValue>是如何用IEnumerable表示的呢?它作为IEnumerable<KeyValuePair<TKey, TValue>>

因此,您可以忽略您有一个字典的事实,而将其视为KeyValuePair<TKey, TValue>对象的枚举。


现在,您已经实现了主要部分,大部分都是正确的。您有一个ItemsControl,正确绑定,并且您将DataTemplate应用于每个项目。但是,请记住,每个项目都是KeyValuePair。因此,TextBlock.Text属性被正确地绑定到Key属性,但是Content被绑定到项目(KeyValuePair<TKey, TValue)本身。这可能是故意的,但我的猜测是,您可能希望ContentControl绑定到Value属性。

第二部分是您希望将ContentTemplate应用于原始DataTemplate中的每个Content。我看到了至少一个,也许两个潜在的错误:

  1. 你的ValuesTemplate似乎是在假设内容是DataTable类型的情况下工作的,当它实际上是KeyValuePair<string, DataTable>类型的时候。在这种情况下,我将Content绑定到Value属性。
  2. 你的ValuesTempalte似乎也将DataGrid.ItemsSource绑定到Values[0]。我在这里的假设是,再次,您认为您的内容是DataTable类型,当它不是,即使是这种情况下,为什么将ItemsSource绑定到DataTable中的第一行?你的DataTable是由行组成的,每一行都是一个序列本身?我猜你只是想做<DataGrid ItemsSource="{Binding}" />

TL;博士;

<!-- Data grid template -->
<DataTemplate x:Key="ValuesTemplate">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock Text="data grid header text" Margin="20,0,0,0" Grid.Row="2" />
    <DataGrid ItemsSource="{Binding}" />
  </Grid>
</DataTemplate>
<!-- List of data tables -->
<ItemsControl ItemsSource="{Binding MyDictionary}" 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>