.NET事件绑定是基于Observer模式的,关于这部分见我的《CLR笔记10.事件》。在.NET2.0中,对Observer进行了一次包装,可以引用System.Component命名空间,实现INotifyPropertyChanged接口,可以获得事件PropertyChanged,以及PropertyChangedEventArgs。于是在这套体系下,事件机制事先搭建好了。
{
public delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);
public interface INotifyPropertyChanged
{
event PropertyChangedEventHandler PropertyChanged;
}
public class PropertyChangedEventArgs : EventArgs
{
public PropertyChangedEventArgs(string propertyName);
public virtual string PropertyName { get; }
}
}
下面看一个例子,这个例子将贯穿本章。
XAML部分:
<Grid>
<TextBlock >Name:</TextBlock>
<TextBox x:Name="nameTextBox" />
<TextBlock >Age:</TextBlock>
<TextBox x:Name="ageTextBox" />
<Button x:Name="birthdayButton" >Birthday</Button>
</Grid>
</Window>
后台代码部分:
{
Person person = new Person("Tom", 9);
public Window1()
{
InitializeComponent();
this.nameTextBox.Text = person.Name;
this.ageTextBox.Text = person.Age.ToString();
// Watch for changes in the controls
this.nameTextBox.TextChanged += nameTextBox_TextChanged;
this.ageTextBox.TextChanged += ageTextBox_TextChanged;
person.PropertyChanged += person_PropertyChanged;
this.birthdayButton.Click += birthdayButton_Click;
}
void person_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Name":
this.nameTextBox.Text = person.Name;
break;
case "Age":
this.ageTextBox.Text = person.Age.ToString();
break;
}
}
void nameTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
person.Name = nameTextBox.Text;
}
void ageTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
int age = 0;
if (int.TryParse(ageTextBox.Text, out age))
{
person.Age = age;
}
}
private void birthdayButton_Click(Object sender, RoutedEventArgs e)
{
++person.Age;
MessageBox.Show(
string.Format(
"Happy Birthday, {0}, age {1}!",
person.Name,
person.Age),
"Birthday");
}
}
辅助类:
{
public Person() { }
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
string name;
public string Name
{
get { return this.name; }
set
{
this.name = value;
OnPropertyChanged("Name");
}
}
int age;
public int Age
{
get { return this.age; }
set
{
this.age = value;
OnPropertyChanged("Age");
}
}
INotifyPropertyChanged Members#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
显示效果: