- DataContext에 전달할 클래스 생성
    - 반드시 INotifyPropertyChanged 인터페이스 구현

- 바인딩 식에서 ValidatesOnException 속성을 true로 설정하면, 바인딩 에러 발생시 지정된 에러메시지가 출력됨








앞에서했던 "RiaINotifyPropertyChanged"파일을 복사하여 "RiaValidation"로 폴더명을 바꾸고 프로젝트를 열어서 실습한다.







[MainPage.xaml]

<UserControl x:Class="RiaSimpleBinding.MainPage"

    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"

    d:DesignHeight="300" d:DesignWidth="400"

    xmlns:me="clr-namespace:RiaSimpleBinding"

    >

    <Grid x:Name="LayoutRoot" Background="White">

        <Grid.Resources>

            <me:PostDateConverter x:Key="pdConverter" />

        </Grid.Resources>

        <StackPanel>

            <TextBlock Text="직접 바인딩" />

            <TextBox x:Name="lblNum" Text="{Binding Path=Num, Mode=TwoWay}" />

            <TextBlock Text="XAML 바인딩" />

            <TextBox Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnExceptions=True}" Width="200" />

            <TextBox Text="{Binding Path=PostDate, Converter={StaticResource pdConverter}, Mode=TwoWay}" />

            <Button x:Name="btnSave" Content="저장" />

            <Button x:Name="btnChanged" Content="코드 비하인드의 값을 변경" />

        </StackPanel>

    </Grid>

</UserControl>

 

 







[MainPage.xaml.cs]

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

 

namespace RiaSimpleBinding

{

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

 

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            btnSave.Click += new RoutedEventHandler(btnSave_Click);

            btnChanged.Click += new RoutedEventHandler(btnChanged_Click);

        }

        // Memo 데이터 한개 바인딩

        private MemoEntity me = new MemoEntity() { Num = 1, Name = "홍길동", PostDate = DateTime.Now };

        void btnChanged_Click(object sender, RoutedEventArgs e)

        {

            me.Num = 2; me.Name = "한라산"; me.PostDate = DateTime.Now.AddDays(1);

        }

 

        void btnSave_Click(object sender, RoutedEventArgs e)

        {

            // UI -> C#으로 데이터 가져오기

            me = this.LayoutRoot.DataContext as MemoEntity;

            if (me != null)

            {

                MessageBox.Show(String.Format("{0}, {1}, {2}", me.Num, me.Name, me.PostDate));

            }

        }

 

        void MainPage_Loaded(object sender, RoutedEventArgs e)

        {

            //[1] 컨트롤에 직접 바인딩

            this.lblNum.Text = me.Num.ToString();

            //[2] XAML 바인딩식을 사용해서 바인딩

            this.LayoutRoot.DataContext = me;

        }

    }

}

 

 






[MemoEntity.cs]

using System;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

 

namespace RiaSimpleBinding

{

    public class MemoEntity : System.ComponentModel.INotifyPropertyChanged

    {

        public int Num { get; set; }

        private string _Name;

        public string Name

        {

            get

            {

                return _Name;

            }

            set

            {

                // 넘겨온 Name 대해서 유효성 검사

                if (value.Length < 2)

                {

                    throw new Exception("이름은 2 이상으로 입력하시오.");

                }

 

                _Name = value;

                if (PropertyChanged != null)

                {

                    // 속성값이 변경되었다면, 동적으로 Name 속성을 반영해라...

                    PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("Name"));

                }

            }

        }

        public DateTime PostDate { get; set; }          

 

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;       

    }

}

 

 






[PostDateConverter.cs]

using System;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Data;

 

namespace RiaSimpleBinding

{

    public class PostDateConverter : IValueConverter

    {

        // 12/10/2009 => 2009 12 10 변환

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

        {

            // 넘겨져 값을 날짜형으로 변환

            DateTime dt = DateTime.Now;

            if (DateTime.TryParse(value.ToString(), out dt))

            {

                return dt.ToString("yyyyMMdd");

            }

            else

            {

                return "";

            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

        {

            DateTime dt = DateTime.Now;

            if (DateTime.TryParse(value.ToString(), out dt))

            {

                return dt;

            }

            return dt;

        }

    }

}

 

 







[실행결과]

--> '솔루션 탐색기'에서 "RiaSimpleBindingTestPage.html"파일을 마우스 우클릭한 후 "브라우저에서 보기"로 실행하여 결과를 확인한다.("F5"로 실행시 예외처리 에러가 난다.)

















Posted by holland14
: