Language/C#_WPF

[C#] 데이터 바인딩

마탁이 2020. 12. 22. 21:35

1. 데이터 바인딩?

 - WPF에서의 바인딩이란 원본 데이터와 화면에 나타난 UI가 서로 연결되어 있다면, 원본 데이터의 값이 바뀌면 UI의 내용도 변경되고 UI의 내용이 변경되면 원본 데이터의 값도 자동으로 바뀌는 동기화.

 - 원본 데이터는 바인딩 소스, 바인딩 원본.

   연결된 UI는 바인딩타겟, 목표 라고 한다.

 - WPF의 바인딩에서 바인드를 시킬 때, 원본 데이터를 직접 연결하지 않고 Property(속성)과 연결한다.

   *Property는 getter/setter를 가지고 있다.

 

 

2. 바인딩 모드

 1) OneWay : 소스 데이터가 변경되면 타겟이 업데이트

 2) TwoWay : 소스 또는 타겟 데이터가 변경되면 다른 한쪽을 업데이트

 3) OneTime : 소스 데이터를 타겟에 반영 후 업데이트 하지 않음

 4) OneWayToSource : 타겟의 변화가 소스에 적용된다. (기본적인 형태의 반대되는 형태)

 

3. 데이터 바인딩 예제 - 1

<Window x:Class="WpfApp1.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"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="Practice Calculator" Height="450" Width="400">

    <StackPanel Margin="10">
        <TextBox Name="txtValue"/>
        <WrapPanel Margin="0, 10">
            <TextBlock Text="Value: " FontWeight="Bold"/>
            <TextBlock Text="{Binding Path=Text, ElementName=txtValue}"/>
        </WrapPanel>
    </StackPanel>
</Window>

 

4. 데이터 바인딩 예제 - 2

<Window x:Class="WpfApp1.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"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="Practice Calculator" Height="450" Width="400">

    <StackPanel>
        <Slider Minimum="1" Maximum="255"
                x:Name="slider"
                IsSnapToTickEnabled="True"/>

        <ProgressBar Minimum="1" Maximum="255"
                     BorderThickness="10"
                     Value="{Binding ElementName=slider,
                                Path=Value, Mode=OneWay}"/>

        <TextBlock Text="{Binding ElementName=slider, 
                                    Path=Value, 
                                    Mode=OneWay}"/>

        <TextBox Text="{Binding ElementName=slider,
                            Path=Value,
                            Mode=OneWay,
                            UpdateSourceTrigger=PropertyChanged}"/>
    </StackPanel>
</Window>

 

5. 바인딩 구문

 - {Binding}

   > 단순히 현재 데이터 컨텍스트를 반환.

 - {Binding Path=속성이름}

   > Path는 바인딩 할 속성을 나타냄.

   > Path가 바인딩의 기본 속성이기 때문에 다음과 같이 생략 가능.

        ->{Binding 속성이름}

 - {Binding Path=Text, ElementName=txtValue}

   > txtValue라는 Name을 가진 Text 속성에 바인딩 하겠다.

 

6. DataContext

 - ElementName 속성처럼 다른 소스를 명시적으로 선언하는게 불필요한 바인딩의 기본 소스.

 - DataContext는 WPF Window를 비롯한 대부분 UI 컨트롤이 상속하는 FrameworkElement 클래스에 정의되어 있다.

    (바인딩의 기초를 지정할 수 있다.)

 - DataContext 속성에 대한 기본 설정은 없다. (처음부터 null 값을 가짐)

 - DataContext는 컨트롤 계층을 통해 상속되므로 Window 자체에 DataContext를 설정한 당ㅁ 모든 자식 컨트롤에 사용할 수 있다.

 

 - e.g)

<Window x:Class="WpfApp1.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"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="Practice Calculator" Height="450" Width="400">

    <StackPanel Margin="15">
        <WrapPanel>
            <TextBlock Text="Window title:  " />
            <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" Width="150" />
        </WrapPanel>
        <WrapPanel Margin="0,10,0,0">
            <TextBlock Text="Window dimensions: " />
            <TextBox Text="{Binding Width}" Width="50" />
            <TextBlock Text=" x " />
            <TextBox Text="{Binding Height}" Width="50" />
        </WrapPanel>
    </StackPanel>
</Window>

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // DataContext가 Window 자체가 되기를 요구
            this.DataContext = this;
        }
    }
}

 * UpdateSourceTrigger=PropertyChanged: 속성 값이바로 입력과 동시에 Changed 발생, 없다면 동시에 변경되지 않음.

'Language > C#_WPF' 카테고리의 다른 글

[C#] 데이터 바인딩 숨김  (0) 2020.12.22
[C#] XAML  (0) 2020.12.21
[C#] WPF  (0) 2020.12.17