[WPF] DataBinding WPF 2012. 3. 14. 16:40

데이터 바인딩은 컨트롤에 데이터를 채우고 동기화 시켜보면 그 내용을 확인 할 수 있다.

바인딩은 말 그대로 데이터를 연결하는 것이다.

다음 예제를 보면 확인 가능하다. 먼저 XAML 코드 아래 다음과 같이 디자인을 한다.

<Window x:Class="WpfApplication4.Window1"       
    xmlns:cs="clr-namespace:WpfApplication4"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="351" Width="500">
    <Window.Resources>
        <cs:NameAdds x:Key="names">
            <cs:NameAdd Name="first" Add="주소1"/>
            <cs:NameAdd Name="second" Add="주소2"/>
            <cs:NameAdd Name="third" Add="주소3"/>
        </cs:NameAdds>           
    </Window.Resources>
    <Grid x:Name="Maingrid" DataContext="{StaticResource names}" >
        <Grid.RowDefinitions>
            <RowDefinition Height="10*" />
            <RowDefinition Height="4*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="2*" />
            <RowDefinition Height="74*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10*" />
            <ColumnDefinition Width="15*" />
            <ColumnDefinition Width="10*" />
            <ColumnDefinition Width="35*" />
            <ColumnDefinition Width="10*" />
        </Grid.ColumnDefinitions>
        <Label Grid.Row="2" Grid.Column="0" Name="label1" Content="성명 : " />
        <TextBox Grid.Row="2" Grid.Column="1"  Name="txtName" Text="{Binding Path=Name}" />
        <Label Grid.Row="2" Grid.Column="2" Name="label2" Content="주소 : " />
        <TextBox Grid.Row="2" Grid.Column="3"  Name="txtAddress" Text="{Binding Path=Add}" />
        <Button Grid.Row="0" Grid.Column="0" Name="insertbutton" Content="추가" Click="insertbutton_Click" Margin="3" ></Button>


        <ListBox Grid.Row="4" Grid.ColumnSpan="5" Name="list" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"
                 FontSize="12" FontWeight="bold" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock>
            <TextBlock Text="{Binding Path=Name}" />
            <TextBlock Text=" :  " />
            <TextBlock Text="{Binding Path=Add}" />
          </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>


위에서 보면  xmlns:cs="clr-namespace:WpfApplication4" 와 같은 부분이 있다. 이는 XAML에서 cs 파일을 가져오기 위한 것인데 무작정 실행하려고 하면 되지 않는다. cs 파일을 정의 한 다음 빌드를 한번 꼭 해주자. 그렇지 않으면 어셈블리가 없다는 오류 메세지가 계속 나올 것이다.

다음은 cs 파일이다.

using System.ComponentModel;
using System.Collections.ObjectModel;


namespace WpfApplication4
{
    public partial class Window1 : Window
    {
        NameAdds nameadds;

        public Window1()
        {
            InitializeComponent();
            nameadds = new NameAdds();
            nameadds = (NameAdds)FindResource("names");
        }

        private void insertbutton_Click(object sender, RoutedEventArgs e)
        {
            nameadds.Add(new NameAdd());
        }
    }


    public class NameAdds : ObservableCollection<NameAdd> { }


    public class NameAdd : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void Notify(string strName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(strName));
            }
        }

        string name = string.Empty;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                Notify("Name");
            }
        }

        string add = string.Empty;
        public string Add
        {
            get { return add; }
            set
            {
                add = value;
                Notify("Add");
            }
        }

        public NameAdd() : this("name", "address") { }
        public NameAdd(string name, string add)
        {
            this.name = name;
            this.add = add;
        }
    }
}

ObservableCollection과 INotifyPropertyChanged은 위에 using 된 부분을 참조 하여 이용한다.

이들은 각기 클래스 항목 변화에 의해 동적 컬렉션을 나타내는 것과 속성 값의 변화를 알리는 역할을 한다.