2013-0219

WPF绑定类属性

作者: momy 分类: 编程开发 0 Comment »
摘要:WPF实现INotifyPropertyChanged接口双向绑定类属性

显示学生信息,当学生姓名发生改变的时候,就需要实时地表现到UI上。

在这种情况下,就需要Student类实现INotifyCollectionChanged接口。

如下:

public class Student : INotifyPropertyChanged
{
string firstName;
public string FirstName { get { return firstName; } set { firstName = value; Notify("FirstName"); } }
string lastName;
public string LastName { get { return lastName; } set { lastName = value; Notify("LastName"); } }
public Student(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
void Notify(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}

  可以看到,实体类Student需要实现的INotifyPropertyChanged 接口成员为:public event PropertyChangedEventHandler PropertyChanged。当我们在WPF的UI控件中实现绑定的时候,UI会自动为PropertyChanged赋值(为UI的控件对象的OnPropertyChanged)。其次,需要在属性SET方法中实现调用委托变量PropertyChanged,即如上代码片段中的Notify。

  设计一个前台界面:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="345" Width="490">
<DockPanel x:Name="dockPanel">
<TextBlock DockPanel.Dock="Top">
<TextBlock>firstName:</TextBlock>
<TextBox Text="{Binding Path=FirstName}" Width="100"></TextBox>
<TextBlock>lastName:</TextBlock>
<TextBox Text="{Binding Path=LastName}" Width="100"></TextBox>
</TextBlock>
<Button x:Name="btnView" DockPanel.Dock="Bottom" Height="30">view</Button>
</DockPanel>
</Window>

  此界面对应后台文件:

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Student student = new Student("firstname1", "lastName1");
dockPanel.DataContext = student;
btnView.Click += new RoutedEventHandler(delegate(object sender, RoutedEventArgs e)
{
MessageBox.Show(student.FirstName);
});
}
}

如果在UI中修改了student的FirstName或者LastName。则后台代码中的student对象的属性会自动同步变化。

标签: WPF INotifyPropertyChanged 阅读: 13729
上一篇: WIN8系统的远程桌面漏洞 利用QQ拼音纯净版实现提权 - 11925次
下一篇: ASP.NET MVC动态生成xml格式的SiteMap - 16544次

向右滑动解锁留言