WPF, XAML

WPF 강좌, 데이터바인딩, DataContext를 이용한 데이터바인딩 심플 예제

OJC 0 73 10.12 16:12

WPF 강좌, 데이터바인딩, DataContext를 이용한 데이터바인딩 심플 예제 

 

콘솔에 츨력을 해야하니 프로젝트 속성에서 출력형식을 "콘솔응용프로그램"으로 설정하자.

 

namespace WpfApplication9

{

    public class Emp

    {

        public string Ename

        {

            get;

            set;

        }

 

        public string City

        {

            get;

            set;

        }

    }

}




<Window x:Class="WpfApplication9.MainWindow"
    xmlns:src="clr-namespace:WpfApplication9"
    Title="Customer Window" 
    Height="300" Width="300">
    <Window.Resources>
        <src:Emp x:Key="emp" Ename="홍길동" City="서울" />
    </Window.Resources>
    <Grid x:Name="Grid1"  DataContext="{StaticResource emp}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0">Name:</TextBlock>
        <TextBlock Grid.Column="0" Grid.Row="1">City:</TextBlock>
        <TextBox x:Name="TextBox1" Grid.Column="1" 
                 Grid.Row="0" Text="{Binding Path=Ename}"></TextBox>
        <TextBox x:Name="TextBox2" Grid.Column="1" 
                 Grid.Row="1" Text="{Binding Path=City}"></TextBox>
        <Button Grid.Column=" 1" Grid.Row="2"   
                Name="button1" Click="OnClicked">Control To Context</Button>
    </Grid>
</Window>




using System.Windows;

namespace WpfApplication9
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnClicked(object sender, RoutedEventArgs args)
        {
            Emp e = Grid1.DataContext as Emp;
            System.Console.WriteLine(e.Ename);
            System.Console.WriteLine(e.City);
        }
    }
}

Comments