Software Development/Application Develop

WPF DataBinding - INotifyPropertyChanged

huiyu 2014. 10. 23. 01:15

DataBinding

1. Person.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBinding_PINotifyPropertyChanged
{
    class Person : INotifyPropertyChanged
    {
        private string name;
        private int _frame;
        
      // Declare the event
      public event PropertyChangedEventHandler PropertyChanged;

      public Person()
      {
      }

      public Person(string value)
      {
          this.name = value;
      }
      public int Frame
      {
          get { return _frame; }
          set
          {
              _frame = value;
              // Call OnPropertyChanged whenever the property is updated
              OnPropertyChanged("Frame");
          }
      }
      public string PersonName
      {
          get { return name; }
          set
          {
              name = value;
              // Call OnPropertyChanged whenever the property is updated
              OnPropertyChanged("PersonName");
          }
      }

      // Create the OnPropertyChanged method to raise the event
      protected void OnPropertyChanged(string name)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(name));
          }
      }
  }
}

2. xaml

<Window x:Class="DataBinding_PINotifyPropertyChanged.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataBinding_PINotifyPropertyChanged"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:Person x:Key="myDataSource" PersonName="abc" Frame="10" />
    </Window.Resources>
    <Grid>
        <TextBox Margin="0,69,0,217">
            <TextBox.Text>
                <Binding Source="{StaticResource myDataSource}" Path="PersonName" UpdateSourceTrigger="PropertyChanged"/>
            </TextBox.Text>
        </TextBox>

        <TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}" Margin="0,143,0,142"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="388,234,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

    </Grid>
</Window>


3. MainWindow.xaml


namespace DataBinding_PINotifyPropertyChanged { /// <summary> /// MainWindow.xaml에 대한 상호 작용 논리 /// </summary> public partial class MainWindow : Window { Person p; public MainWindow() { InitializeComponent(); p = Resources["myDataSource"] as Person; p.PersonName = "a"; } private void Button_Click(object sender, RoutedEventArgs e) { p.Frame++; p.PersonName = p.PersonName + "b" + "C"; } } }




728x90