深入浅出WPF 第二部分(1)
第二部分 游历WPF内部世界
第6章 深入浅出话Binding
6.1 Data Binding在WPF中的地位
应用程序会具有三层结构,即数据存储层、数据处理层和数据展示层。存储层相当于一个城市的仓储区,由数据库和文件系统构成;处理层更正确的称呼应该是逻辑层,与业务逻辑有关、用于加工处理数据的算法都集中在这里;展示层的功能是把加工后的数据通过可视的界面展示给用户或者通过其他种类的接口展示给别的应用程序。
程序的本质是数据加算法。
6.2 Binding基础
[csharp]
using System.ComponentModel;
namespace FirstWpfApplication.Objects
{
class Student : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return this.name; }
set
{
this.name = value;
//激发System.ComponentModel.INotifyPropertyChanged.PropertyChanged事件
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
using System.ComponentModel;
namespace FirstWpfApplication.Objects
{
class Student : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return this.name; }
set
{
this.name = value;
//激发System.ComponentModel.INotifyPropertyChanged.PropertyChanged事件
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
[html]
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="5"/>
<RowDefinition Height="25"/>
<RowDefinition Height="5"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<TextBox x:Name="textBox1" BorderBrush="Black" Grid.Row="0"/>
<TextBox x:Name="textBox2" BorderBrush="Black" Grid.Row="2"/>
<Button x:Name="button1" Content="OK" Click="button1_Click" Grid.Row="4"/>
</Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="5"/>
<RowDefinition Height="25"/>
<RowDefinition Height="5"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<TextBox x:Name="textBox1" BorderBrush="Black" Grid.Row="0"/>
<TextBox x:Name="textBox2" BorderBrush="Black" Grid.Row="2"/>
<Button x:Name="button1" Content="OK" Click="button1_Click" Grid.Row="4"/>
</Grid>
[csharp]
public partial class MainWindow : Window
{
Student stu;
public MainWindow()
{
InitializeComponent();
stu = new Student();
Binding binding = new Binding();
binding.Source = stu;
binding.Path = new PropertyPath("Name");
BindingOperations.SetBinding(this.textBox1, TextBox.TextProperty, binding);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
stu.Name =textBox2.Text;
}
}
public partial class MainWindow : Window
{
Student stu;
public MainWindow()
{
InitializeComponent();
stu = new Student();
Binding binding = new Binding();
binding.Source = stu;
binding.Path = new PropertyPath("Name");
BindingOperations.SetBinding(this.textBox1, TextBox.TextProperty, binding);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
stu.Name =textBox2.Text;
}
}