728x90
데이터 바인딩의 이해를 위해 간단하게 https://clear-sky-sun.tistory.com/3에서 설명을 확인 할 수 있습니다.
1. 구성
단방향 바인딩과, 양방향 바인딩에 대해 실습을 해보려고 합니다.
간단한 실습을 통해, 코더를 하나씩 작성하여, 이해 하시기 바랍니다.
2. 단반향 바인딩 진행
One_Way_Data_Binding.xaml
<Grid>
<StackPanel Name = "Display">
<StackPanel Orientation = "Horizontal" Margin = "50, 50, 0, 0">
<TextBlock Text = "Name : " Margin = "10" Width = "100"/>
<TextBlock Margin = "10" Width = "100" Text = "{Binding Name}"/>
</StackPanel>
<StackPanel Orientation = "Horizontal" Margin = "50,0,50,0">
<TextBlock Text = "Age : " Margin = "10" Width = "100"/>
<TextBlock Margin = "10" Width = "200" Text = "{Binding Age}" />
</StackPanel>
</StackPanel>
</Grid>
One_Way_Data_Binding.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
DataContext = Et.GetEt();
}
}
public class Et
{
public string Name { get; set; }
public string Age { get; set; }
public static Et GetEt()
{
var emp = new Et()
{
Name = "Gelato",
Age = "20's"
};
return emp;
}
}
결과
3. 양방향 바인딩 진행
Tow_Way_Data_Binding.xaml
<Grid.RowDefinitions>
<RowDefinition Height = "Auto" />
<RowDefinition Height = "Auto" />
<RowDefinition Height = "*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width = "Auto" />
<ColumnDefinition Width = "200" />
</Grid.ColumnDefinitions>
<TextBlock Name = "nameLabel" Margin = "200,20,0,0">Name:</TextBlock>
<TextBox Name = "nameText" Grid.Column = "1" Margin = "10,20,0,0"
Text = "{Binding Name, Mode = TwoWay}"/>
<TextBlock Name = "ageLabel" Margin = "200,20,0,0"
Grid.Row = "1">Age:</TextBlock>
<TextBox Name = "ageText" Grid.Column = "1" Grid.Row = "1" Margin = "10,20,0,0"
Text = "{Binding Age, Mode = TwoWay}"/>
<StackPanel Grid.Row = "2" Grid.ColumnSpan = "2">
<Button Content = "Display" Click = "Button_Click"
Margin = "200,20,0,0"/>
<TextBlock x:Name = "txtblock" Margin = "200,20,0,0"/>
</StackPanel>
Tow_Way_Data_Binding.xaml.cs
using Windows.UI.Xaml.Controls;
public sealed partial class MainPage : Page
{
Person person = new Person { Name = "철수", Age = 27 };
public MainPage()
{
this.InitializeComponent();
this.DataContext = person;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string message = person.Name + " is " + person.Age + " years old";
txtblock.Text = message;
}
}
public class Person
{
private string nameValue;
public string Name
{
get { return nameValue; }
set { nameValue = value; }
}
private double ageValue;
public double Age
{
get { return ageValue; }
set
{
if (value != ageValue)
{
ageValue = value;
}
}
}
}
결과
728x90
'C#' 카테고리의 다른 글
C# 네비게이션 구현하기 (1) | 2020.02.16 |
---|---|
C# 버튼 다루기 (0) | 2020.02.16 |
C# Windows 계산기 만들기 _ 간단한 계산기 (0) | 2020.02.16 |
데이터 바인딩이란? _간단하게 이해하기 (0) | 2020.02.16 |
C# random() 함수 사용하기(랜덤 숫자 생성) (0) | 2020.02.16 |