如何:绑定两个控件的属性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

下面的示例演示如何将 CanvasBackground 属性绑定到 SelectedItemContentThe 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