FrameworkElement.DataContext 속성

정의

FrameworkElement에 대한 데이터 컨텍스트를 가져오거나 설정합니다. 데이터 컨텍스트의 일반적인 사용은 가 FrameworkElement{Binding} 태그 확장을 사용하고 데이터 바인딩에 참여하는 경우입니다.

public:
 property Platform::Object ^ DataContext { Platform::Object ^ get(); void set(Platform::Object ^ value); };
IInspectable DataContext();

void DataContext(IInspectable value);
public object DataContext { get; set; }
var object = frameworkElement.dataContext;
frameworkElement.dataContext = object;
Public Property DataContext As Object
<frameworkElement DataContext="binding"/>
- or -
<frameworkElement DataContext="{StaticResource keyedObject}"/>

속성 값

Object

Platform::Object

IInspectable

데이터 컨텍스트로 사용할 개체입니다.

예제

다음은 를 사용자 지정 클래스의 instance 직접 설정하는 DataContext 예제입니다.

C++/WinRT{Binding} 태그 확장을 사용하는 경우 속성과 BindableAttribute를 사용합니다FrameworkElement::DataContext. {x:Bind} 태그 확장을 사용하는 경우 도 BindableAttribute사용하지 FrameworkElement::DataContext 않습니다.

아래 C++/WinRT 코드 예제(예: 파일 목록을 사용하는 .idl 방법 및 이를 위해 생성하는 구현 파일로 수행할 작업)에 대한 자세한 배경은 XAML 컨트롤, C++/WinRT 속성에 바인딩을 참조하세요.

// MyColors.idl
namespace MyColorsApp
{
    [bindable]
    [default_interface]
    runtimeclass MyColors : Windows.UI.Xaml.Data.INotifyPropertyChanged
    {
        MyColors();
        Windows.UI.Xaml.Media.SolidColorBrush Brush1;
    }
}

// MyColors.h
#pragma once
#include "MyColors.g.h"
namespace winrt::MyColorsApp::implementation
{
    struct MyColors : MyColorsT<MyColors>
    {
        MyColors() = default;

        Windows::UI::Xaml::Media::SolidColorBrush Brush1();
        void Brush1(Windows::UI::Xaml::Media::SolidColorBrush const& value);
        winrt::event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler);
        void PropertyChanged(winrt::event_token const& token) noexcept;

    private:
        Windows::UI::Xaml::Media::SolidColorBrush m_brush1{ nullptr };
        winrt::event<Windows::UI::Xaml::Data::PropertyChangedEventHandler> m_propertyChanged;
    };
}

namespace winrt::MyColorsApp::factory_implementation
{
    struct MyColors : MyColorsT<MyColors, implementation::MyColors>
    {
    };
}

// MyColors.cpp
#include "pch.h"
#include "MyColors.h"

namespace winrt::MyColorsApp::implementation
{
    Windows::UI::Xaml::Media::SolidColorBrush MyColors::Brush1()
    {
        return m_brush1;
    }

    void MyColors::Brush1(Windows::UI::Xaml::Media::SolidColorBrush const& value)
    {
        if (m_brush1 != value)
        {
            m_brush1 = value;
            m_propertyChanged(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs{ L"Brush1" });
        }
    }

    winrt::event_token MyColors::PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler)
    {
        return m_propertyChanged.add(handler);
    }

    void MyColors::PropertyChanged(winrt::event_token const& token) noexcept
    {
        m_propertyChanged.remove(token);
    }
}

<!-- MainPage.xaml-->
...
<TextBox x:Name="MyTextBox" Background="{Binding Brush1}"/>
...

// MainPage.h
...
#include "MyColors.h"
#include "MainPage.g.h"
...

// MainPage.cpp
#include "pch.h"
#include "MainPage.h"

using namespace winrt;
using namespace Windows::UI;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Media;

namespace winrt::MyColorsApp::implementation
{
    MainPage::MainPage()
    {
        InitializeComponent();

        // Create an instance of the MyColors class
        // which implements INotifyPropertyChanged.
        winrt::MyColorsApp::MyColors textcolor{ winrt::make<winrt::MyColorsApp::implementation::MyColors>() };

        // Set the Brush1 property value to a new SolidColorBrush
        // with the color Red.
        textcolor.Brush1(SolidColorBrush(Colors::Red()));

        // Set the DataContext of the TextBox named MyTextBox.
        MyTextBox().DataContext(textcolor);
    }
...
}
// Create an instance of the MyColors class 
// that implements INotifyPropertyChanged.
MyColors textcolor = new MyColors();

// Brush1 is set to be a SolidColorBrush with the value Red.
textcolor.Brush1 = new SolidColorBrush(Colors.Red);

// Set the DataContext of the TextBox MyTextBox.
MyTextBox.DataContext = textcolor;

설명

데이터 컨텍스트 는 개체가 개체 관계 계층의 연속 부모 개체에서 데이터 바인딩 정보를 상속할 수 있는 개념입니다.

데이터 컨텍스트의 가장 중요한 측면은 데이터 바인딩에 사용되는 데이터 원본입니다. 의 일반적인 사용 DataContext 은 데이터 원본 개체로 직접 설정하는 것입니다. 이 데이터 원본은 비즈니스 개체와 같은 클래스의 instance 수 있습니다. 또는 데이터 컨텍스트가 지원 컬렉션의 변경 내용을 검색할 수 있도록 관찰 가능한 컬렉션으로 데이터 원본을 만들 수 있습니다. 데이터 원본이 프로젝트에 포함된 라이브러리에 의해 정의된 경우 을 설정하는 DataContext 것은 ResourceDictionary에서 데이터 원본을 키 리소스로 인스턴스화한 다음 {StaticResource} 태그 확장 참조를 사용하여 XAML에서 를 설정하는 DataContext 것과 결합되는 경우가 많습니다.

설정하는 DataContext 또 다른 방법은 를 호출 InitializeComponent한 직후 앱 초기화 논리의 일부로 런타임 개체 트리의 루트에 추가하는 것입니다. 이 기술은 데이터 바인딩 개요에 나와 있습니다.

데이터 컨텍스트는 원본을 지정하는 것 외에도 데이터 원본에 대한 경로와 같은 바인딩 선언의 추가 특성을 저장할 수 있습니다.

DataContext 설정하면 동일한 개체에서 여러 속성의 여러 바인딩을 공유 데이터 컨텍스트로 설정하는 데 편리합니다. 그러나 가 정의되지 않고 필요한 모든 바인딩 자격이 별도의 바인딩 문에 존재하는 것이 유효 DataContext 합니다.

개체 데이터 원본을 구현하는 방법은 요구 사항 및 프로그래밍 언어에 따라 달라집니다. 자세한 내용은 데이터 바인딩 심층 분석을 참조하세요.

C# 데이터 컨텍스트의 일반적인 시나리오는 변경 알림을 지원하는 CLR 정의 비즈니스 개체를 사용하는 것입니다. 비즈니스 개체의 경우 데이터 컨텍스트로 사용되는 사용자 지정 클래스 는 일반적으로 INotifyPropertyChanged를 구현하므로 데이터에 대한 업데이트가 단방향 또는 양방향 바인딩을 업데이트할 수 있습니다. 데이터 원본이 비즈니스 개체의 컬렉션인 경우 INotifyCollectionChanged 및 목록 지원(IList 또는 List)을 구현하거나 ObservableCollection에서 파생될 수 있습니다.

적용 대상

추가 정보