Share via


HOW TO:繫結至集合並根據選取項目顯示資訊

在簡單的主從式案例中,您有資料繫結 ItemsControl,例如 ListBox。 根據使用者選取項目,您會顯示所選項目的詳細資訊。 這個範例顯示如何實作此案例。

範例

在這個範例中,People 是 Person 類別 (Class) 的 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。 不過,如果 ListBox 是從 CollectionViewSource 取得其資料,則它會自動同步 (Synchronize) 選取項目與貨幣。

請注意,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();
}

請參閱

工作

HOW TO:使用含階層式資料的主從式模式

HOW TO:使用含階層式 XML 資料的主從式模式

概念

資料繫結概觀

資料範本化概觀

其他資源

資料繫結 HOW TO 主題