본문 바로가기
C#/WPF

DataContext Binding

by Falto 2023. 3. 1.

별도의 타겟을 지정하지 않고 Path만 써 놓으면 DataContext를 읽게 된다. DataContext는 기본적으로 null이기 때문에, 개발자가 직접 지정해주어야 한다.

<Window x:Class="IamNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Height="450" Width="450" Background="Black"
        Title="{Binding Path=ActualWidth}">
</Window>

위는 xaml, 아래는 cs

using System.Windows;

namespace IamNamespace
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }
    }
}

이렇게 하면 MainWindow의 Title에 ActualWidth를 바인딩할 수 있다.

댓글