1.自定义生成的persons类 继承INotifyPropertyChanged接口。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace 数据绑定事件
{
class Persons:INotifyPropertyChanged
{
private string _name;
private int _age;
public string Name
{
get { return _name; }
set {_name = value; }
}
public int Age
{
get { return _age;}
set
{
_age = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
2.定义事件public event PropertyChangedEventHandler PropertyChanged;,在值进行修改的set属性触发事件PropertyChanged(this, new PropertyChangedEventArgs("Age"));
3.using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace 数据绑定事件
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Persons p = new Persons();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
p.Name = "王运波";
p.Age = 18;
tb_name.DataContext = p;
tb_age.DataContext = p;
}
在窗体加载时,绑定控件的数据上下文为persons类的实例化对象p。
4. <TextBox Text="{Binding Age}" Height="23" HorizontalAlignment="Left" Margin="79,130,0,0" Name="tb_age" VerticalAlignment="Top" Width="120" />
在Xaml中将控件的Binding属性,绑定到类属性。
写的不够形象,不理解的再找我讨论。 |