Share via


如何:绑定到集合并基于选择显示信息

更新:2007 年 11 月

在一个简单的主-从方案中,您有一个已绑定数据的 ItemsControl,例如 ListBox。基于用户的选择显示有关选定项的更多信息。此示例演示如何实现该方案。

示例

在此示例中,People 是 Person 类的一个 ObservableCollection<T>。该 Person 类包含三个属性:FirstName、LastName 和 HomeTown,它们的类型均为 string。

<Window x:Class="SDKSample.Window1"
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:SDKSample"
  Title="Binding to a Collection"
  SizeToContent="WidthAndHeight">
  <Window.Resources>
    <local:People x:Key="MyFriends"/>


...


  </Window.Resources>

  <StackPanel>
    <TextBlock FontFamily="Verdana" FontSize="11"
               Margin="5,15,0,10" FontWeight="Bold">My Friends:</TextBlock>
    <ListBox Width="200" IsSynchronizedWithCurrentItem="True"
             ItemsSource="{Binding Source={StaticResource MyFriends}}"/>
    <TextBlock FontFamily="Verdana" FontSize="11"
               Margin="5,15,0,5" FontWeight="Bold">Information:</TextBlock>
    <ContentControl Content="{Binding Source={StaticResource MyFriends}}"
                    ContentTemplate="{StaticResource DetailTemplate}"/>
  </StackPanel>
</Window>

ContentControl 使用以下 DataTemplate,该模板定义如何显示 Person 的信息:

<DataTemplate x:Key="DetailTemplate">
  <Border Width="300" Height="100" Margin="20"
          BorderBrush="Aqua" BorderThickness="1" Padding="8">
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
      </Grid.ColumnDefinitions>
      <TextBlock Grid.Row="0" Grid.Column="0" Text="First Name:"/>
      <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=FirstName}"/>
      <TextBlock Grid.Row="1" Grid.Column="0" Text="Last Name:"/>
      <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=LastName}"/>
      <TextBlock Grid.Row="2" Grid.Column="0" Text="Home Town:"/>
      <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=HomeTown}"/>
    </Grid>
  </Border>
</DataTemplate>

以下是该示例生成的内容的一个屏幕快照。ContentControl 显示所选人员的其他属性。

绑定到集合

此示例中需要注意的两点是:

  1. ListBoxContentControl 绑定到同一个源。两个绑定的 Path 属性均未指定,因为两个控件都绑定到整个集合对象。

  2. 为此,必须将 IsSynchronizedWithCurrentItem 属性设置为 true。设置此属性可以确保选定项始终设置为 CurrentItem。或者,如果 ListBoxCollectionViewSource 获取数据,则它将自动同步选定内容和当前内容。

请注意,Person 类按以下方式重写 ToString 方法。默认情况下,ListBox 调用 ToString 并显示绑定集合中每个对象的字符串表示形式。因此,每个 Person 都显示为 ListBox 中的第一个名称。

Public Overrides Function ToString() As String
    Return Me._firstname.ToString
End Function
public override string ToString()
{
    return firstname.ToString();
}

有关完整示例,请参见 绑定到集合的示例

请参见

任务

如何:对分层数据使用主-从模式

如何:对分层 XML 数据使用主-从模式

概念

数据绑定概述

数据模板化概述

其他资源

数据绑定示例

数据绑定帮助主题