次の方法で共有


方法: コレクションにバインドし、選択に基づいて情報を表示する

簡単なマスター詳細シナリオでは、ListBox などのデータ バインドされた ItemsControl があります。 ユーザーの選択に基づいて、選択した項目に関する詳細情報を表示します。 この例では、このシナリオを実装する方法を示します。

この例では、PeoplePerson クラスの ObservableCollection<T> です。 この Person クラスには、FirstNameLastName、および HomeTownという 3 つのプロパティがあり、すべてが string型です。

<Window x:Class="SDKSample.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://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 では、Person の情報の表示方法を定義する次の DataTemplate を使用します。

<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 には、選択したユーザーの他のプロパティが表示されます。

コレクションへのバインディング へのバインド

この例で注目すべき 2 つの点は次のとおりです。

  1. ListBoxContentControl は、同じソースにバインドされます。 両方のコントロールがコレクション オブジェクト全体にバインドされるため、両方のバインディングの Path プロパティは指定されません。

  2. これを機能させるには、IsSynchronizedWithCurrentItem プロパティを true に設定する必要があります。 このプロパティを設定すると、選択した項目が常に CurrentItemとして設定されます。 または、ListBoxCollectionViewSourceからデータを取得すると、選択と通貨が自動的に同期されます。

Person クラスは、次のように ToString メソッドをオーバーライドすることに注意してください。 既定では、ListBoxToString を呼び出し、バインドされたコレクション内の各オブジェクトの文字列表現を表示します。 そのため、各 PersonListBoxに名として表示されます。

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

関連項目