방법: XAML의 바인딩에 사용할 수 있는 데이터 만들기

이 토픽에서는 애플리케이션의 요구 사항에 따라 XAML(Extensible Application Markup Language)에서 바인딩을 위해 데이터가 제공되도록 하는 다양한 방법을 설명합니다.

예제

XAML에서 바인딩하려는 CLR(공용 언어 런타임) 개체가 있는 경우 바인딩에 개체를 사용할 수 있도록 하는 한 가지 방법은 이를 리소스로 정의하고 x:Key를 제공하는 것입니다. 다음 예제에는 문자열 속성 이름이 PersonNamePerson 개체가 있습니다. Person 개체(<src> 요소를 포함하는 강조 표시된 줄에 표시됨)는 SDKSample이라는 네임스페이스에 정의되어 있습니다.

<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> 요소가 포함된 강조 표시된 줄에서 보여주는 것과 같이 XAML의 개체에 TextBlock 컨트롤을 바인딩할 수 있습니다.

또는 다음 예제에서와 같이 ObjectDataProvider 클래스를 사용할 수 있습니다.

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

  <Window.Resources>
    <ObjectDataProvider x:Key="myDataSource" ObjectType="{x:Type src:Person}">
      <ObjectDataProvider.ConstructorParameters>
        <system:String>Joe</system:String>
      </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
    <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"/>
    </Style>
  </Window.Resources>

  <Border Margin="25" BorderBrush="Aqua" BorderThickness="3" Padding="8">
    <DockPanel Width="200" Height="100">
      <Label>Enter a Name:</Label>
      <TextBox>
        <TextBox.Text>
          <Binding Source="{StaticResource myDataSource}" Path="Name"
                   UpdateSourceTrigger="PropertyChanged"/>
        </TextBox.Text>
      </TextBox>

      <Label>The name you entered:</Label>
      <TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=Name}"/>
    </DockPanel>
  </Border>
</Window>

<TextBlock> 요소가 포함된 강조 표시된 줄에서 보여주는 것과 같이 동일한 방식으로 바인딩을 정의합니다.

이 특정 예제에서 결과는 동일합니다. 텍스트 콘텐츠 Joe가 포함된 TextBlock이 있습니다. 하지만 ObjectDataProvider 클래스는 메서드의 결과에 바인딩하는 것과 같은 기능을 제공합니다. 제공되는 기능이 필요한 경우 ObjectDataProvider 클래스를 사용할 수 있습니다.

하지만 이미 만들어진 개체에 바인딩하는 경우 다음 예제와 같이 코드에서 DataContext를 설정해야 합니다.

DataSet myDataSet;

private void OnInit(object sender, EventArgs e)
{
  string mdbFile = Path.Combine(AppDataPath, "BookData.mdb");
  string connString = string.Format(
      "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", mdbFile);
  OleDbConnection conn = new OleDbConnection(connString);
  OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM BookTable;", conn);

  myDataSet = new DataSet();
  adapter.Fill(myDataSet, "BookTable");

  // myListBox is a ListBox control.
  // Set the DataContext of the ListBox to myDataSet
  myListBox.DataContext = myDataSet;
}
Private myDataSet As DataSet

Private Sub OnInit(ByVal sender As Object, ByVal e As EventArgs)
  Dim mdbFile As String = Path.Combine(AppDataPath, "BookData.mdb")
  Dim connString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", mdbFile)
  Dim conn As New OleDbConnection(connString)
  Dim adapter As New OleDbDataAdapter("SELECT * FROM BookTable;", conn)

  myDataSet = New DataSet()
  adapter.Fill(myDataSet, "BookTable")

  ' myListBox is a ListBox control.
  ' Set the DataContext of the ListBox to myDataSet
  myListBox.DataContext = myDataSet
End Sub

XmlDataProvider 클래스를 사용하여 바인딩을 위한 XML 데이터에 액세스하려면 XMLData Provider 및 XPath 쿼리를 사용하여 XML 데이터에 바인딩을 참조하세요. ObjectDataProvider 클래스를 사용하여 바인딩할 XML 데이터에 액세스하려면 XDocument, XElement 또는 LINQ for XML 쿼리 결과에 바인딩을 참조하세요.

바인딩할 데이터를 지정할 수 있는 여러 가지 방법에 대한 자세한 내용은 바인딩 원본 지정을 참조하세요. 바인딩할 수 있는 데이터 형식 또는 바인딩에 대해 CLR(공용 언어 런타임) 개체를 구현하는 방법에 대한 자세한 내용은 바인딩 원본 개요를 참조하세요.

참고 항목