WPF 双向绑定

定义类: 类实现INotifyPropertyChanged 接口

 1 using Microsoft.Win32;
 2 using System.ComponentModel;
 3 using System.Windows;
 4 
 5 namespace WPFEntity
 6 {
 7     public class Person : INotifyPropertyChanged
 8     {
 9         private int age;
10 
11         public event PropertyChangedEventHandler PropertyChanged;
12 
13         public int Age
14         {
15             get { return this.age; }
16             set
17             {
18                 this.age = value;
19                 if (this.PropertyChanged != null)
20                 {
21                     this.PropertyChanged(this, new PropertyChangedEventArgs("Age"));
22                 }
23             }
24         }
25 
26         public string Name { get; set; }
27     }
28 }

 

.cs文件绑定:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
            btnAddAge.Click += btnAddAge_Click;
        }

        Person person = new Person();

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            person.Name = "Nelson";
            person.Age = 24;
            grid1.DataContext = person;
        }

        void btnAddAge_Click(object sender, RoutedEventArgs e)
        {
            person.Age++;
        }
    }

 

XAML代码:

<TextBox Name="txtName" Text="{Binding Name}" HorizontalAlignment="Left" Height="23" Margin="83,74,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<TextBox Name="txtAge" Text="{Binding Age}" HorizontalAlignment="Left" Height="23" Margin="83,131,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Name="btnAddAge" Content="Age增加" HorizontalAlignment="Left" Margin="274,75,0,0" VerticalAlignment="Top" Width="75"/>
        

 

 

 

 

 

posted on 2013-11-29 16:16  天蝎座筷子  阅读(421)  评论(0编辑  收藏  举报

导航