创建一个WPF窗体,加一个TextBox和Button控件,控件button用于控制数据更改,TextBox用于显示更改后的数据,这项数据对于WinForm来说是很容易实现的,用控件点击事件对另一个控件访问,控制控件的刷新。但是在WPF中,控件刷新完全由数据驱动,使用数据绑定,当数据变化时自动更新控件。在大量的数据和剧烈的变化中,这种数据驱动的方式更加有优势。
代码实现如下:
//创建一个Student类,需要继承INotifyPropetyChanged接口
public class Student : INotifyPropertyChanged
{
//构造函数
public Student(string name,int age)
{
this.age = age;
this.name = name;
}
private string name;
private int age;
public event PropertyChangedEventHandler PropertyChanged;
public int getAge
{
get { return age; }
set {
age = value;
if (PropertyChanged != null)
{
//给getAge赋值时触发事件
this.PropertyChanged.Invoke(this,new PropertyChangedEventArgs("getAge"));
}
}
}
}
窗体设计器代码很简单,如下代码:
<Window x:Class="WPFtest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFtest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="91*"/>
<RowDefinition Height="93*"/>
<RowDefinition Height="136*"/>
</Grid.RowDefinitions>
<TextBox x:Name="tbx" HorizontalAlignment="Left" Height="43" Margin="128,26,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="269"/>
<Button x:Name="btn" Content="ClickMe" HorizontalAlignment="Left" Margin="208,54,0,0" Grid.Row="2" VerticalAlignment="Top" Width="75" Click="btn_Click"/>
</Grid>
</Window>
下面是逻辑代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//新建绑定类,引用为System.Windows.Data
Binding newbind = new Binding();
//绑定源为Student的实例stu1
newbind.Source = stu1;
//绑定属性为"getAge"
newbind.Path = new PropertyPath("getAge");
//设置绑定TextBox控件,显示在TextProperty中
//TextBox是System.Windows.Controls中的,不是System.Windows.Forms中的,需要注意
tbx.SetBinding(TextBox.TextProperty,newbind);
}
//新建实例
public Student stu1 = new Student("123",16);
private void btn_Click(object sender, RoutedEventArgs e)
{
//自加1
stu1.getAge += 1;
}
}
实现效果如下:
至此,实例已完成。