HOW TO:繫結兩個控制項的屬性How to: Bind the Properties of Two Controls

此範例示範如何具現化控制項屬性繫結至另一個使用ElementName屬性。This example shows how to bind the property of one instantiated control to that of another using the ElementName property.

範例Example

下列範例示範如何繫結Background的屬性CanvasSelectedItemContentThe following example shows how to bind the Background property of a Canvas to the SelectedItem.Content 屬性ComboBox:property of a ComboBox:

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://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>

此範例轉譯後會如同以下所示︰When this example is rendered it looks like the following:

顯示下拉式選取綠色值方塊和綠色方形的螢幕擷取畫面。

注意

繫結目標屬性 (在此範例中,Background屬性) 必須是相依性屬性。The binding target property (in this example, the Background property) must be a dependency property. 如需詳細資訊,請參閱 資料繫結概觀For more information, see Data Binding Overview.

另請參閱See also