방법: 단순 바인딩 만들기

다음 예제는 단순한 Binding를 만드는 방법을 보여줍니다.

예제

이 예제에는 문자열 속성 이름이 PersonNamePerson 개체가 있습니다. Person 개체는 SDKSample라는 네임스페이스에 정의됩니다.

다음 예제의 <src> 요소를 포함하는 강조 표시된 줄은 JoePersonName 속성 값으로 Person 개체를 인스턴스화합니다. 이 작업은 Resources 섹션에서 수행되며 x:Key가 할당됩니다.

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:src="clr-namespace:SDKSample"
  SizeToContent="WidthAndHeight"
  Title="Simple Data Binding Sample">

  <Window.Resources>
    <src:Person x:Key="myDataSource" PersonName="Joe"/>
    <Style TargetType="{x:Type Label}">
      <Setter Property="DockPanel.Dock" Value="Top"/>
      <Setter Property="FontSize" Value="12"/>
    </Style>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="Width" Value="100"/>
      <Setter Property="Height" Value="25"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
    </Style>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Width" Value="100"/>
      <Setter Property="Height" Value="25"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
      <Setter Property="Padding" Value="3"/>
    </Style>
  </Window.Resources>
  <Border Margin="5" BorderBrush="Aqua" BorderThickness="1" Padding="8" CornerRadius="3">
    <DockPanel Width="200" Height="100" Margin="35">
      <Label>Enter a Name:</Label>
      <TextBox>
        <TextBox.Text>
          <Binding Source="{StaticResource myDataSource}" Path="PersonName"
                   UpdateSourceTrigger="PropertyChanged"/>
        </TextBox.Text>
      </TextBox>
      
      <Label>The name you entered:</Label>
      <TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}"/>
    </DockPanel>
  </Border>
</Window>

그러면 <TextBlock> 요소를 포함하는 강조 표시된 줄이 TextBlock 컨트롤을 PersonName 속성에 바인딩합니다. 따라서 TextBlock이 값 "Joe"와 함께 나타납니다.

참고 항목