次の方法で共有


方法 : 2 つのコントロールのプロパティをバインドする

更新 : 2007 年 11 月

この例では、ElementName プロパティを使用して、インスタンス化された 1 つのコントロールのプロパティを別のコントロールのプロパティにバインドする方法を説明します。

使用例

CanvasBackground プロパティを ComboBoxSelectedItem.Content プロパティにバインドする方法を次の例に示します。

<Window
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  Width="460" Height="200"
  Title="Binding the Properties of Two Controls">

  <Window.Resources>
    <Style TargetType="TextBlock">
      <Setter Property="FontSize" Value="16"/>
      <Setter Property="FontWeight" Value="Bold"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
      <Setter Property="HorizontalAlignment" Value="Center"/>
    </Style>
    <Style TargetType="Canvas">
      <Setter Property="Height" Value="50"/>
      <Setter Property="Width" Value="50"/>
      <Setter Property="Margin" Value="8"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
    </Style>
    <Style TargetType="ComboBox">
      <Setter Property="Width" Value="150"/>
      <Setter Property="Margin" Value="8"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
    </Style>
  </Window.Resources>

  <Border Margin="10" BorderBrush="Silver" BorderThickness="3" Padding="8">
    <DockPanel>
      <TextBlock>Choose a Color:</TextBlock>
      <ComboBox Name="myComboBox" SelectedIndex="0">
        <ComboBoxItem>Green</ComboBoxItem>
        <ComboBoxItem>Blue</ComboBoxItem>
        <ComboBoxItem>Red</ComboBoxItem>
      </ComboBox>
      <Canvas>
        <Canvas.Background>
          <Binding ElementName="myComboBox" Path="SelectedItem.Content"/>
        </Canvas.Background>
      </Canvas>
    </DockPanel>
  </Border>
</Window>

この例をレンダリングすると、次のようになります。

背景が緑のキャンバス

サンプル全体については、「UI 要素のプロパティのバインディングのサンプル」を参照してください。

メモ   バインディング ターゲット プロパティ (この例では Background プロパティ) は、依存関係プロパティである必要があります。詳細については、「データ バインディングの概要」を参照してください。

参照

処理手順

方法 : バインディング ソースを指定する

その他の技術情報

データ バインディングのサンプル

データ バインディングに関する「方法」トピック