1 . 当需要从UI层收集用户的输入信息时,此时 source是UI层的控件–target是业务逻辑层的对象;
这个时候数据流向是 UI(source)---->实例类对象(target),需要借助wpf中的依赖对象与依赖属性机制实现数据绑定
- 预备知识
从程序在内存中的结构来看, 静态字段在内存中只有一个拷贝,非静态字段则是每个实例拥有一个拷贝;
无论方法是否为静态的,在内存中只会有一份拷贝,区别只是通过类名来访问存放指令的内存,还是通过实例名来访问存放指令的内存。
实例的每个CLR属性都包装着一个非静态的字段。
DependencyObject是wpf底层的基类,wpf所有的UI控件都是依赖对象。
对业务逻辑层的实例类添加依赖属性,使其可以作为binding的target。
3. 示例代码
实例类代码
using System.Windows;
using System.Windows.Data;
namespace textboxBinding
{
public class Cstudent:DependencyObject
{
/// 使用 code Snippet 中propdp,按tab键自动添加依赖属性
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
// Using a DependencyProperty as the backing store for Name. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(Cstudent));
//由snippet自动生成的代码中,第四个参数类型PropertyMetadata类,其中DefaultValue若未被赋值,则在读取时,会抛出异常
//setBinding
public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding)
{
return BindingOperations.SetBinding(this, dp, binding);
}
}
}
xaml代码
<Window x:Class="textboxBinding.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:textboxBinding"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel Margin="10">
<TextBlock Text="用户输入:" Margin="10,4,4,0"/>
<TextBox x:Name="textBox1" Margin="10"/>
<TextBlock Text="显示输入:" Margin="10,4,4,0"/>
<TextBox x:Name="textBox2" Margin="10"/>
</StackPanel>
</Window>
后台代码
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace textboxBinding
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Cstudent stu;
public MainWindow()
{
InitializeComponent();
stu = new Cstudent();
//将textbox1的输入绑定到Cstudent.NameProperty 属性
///UI控件---->对象
stu.SetBinding(Cstudent.NameProperty, new Binding("Text") { Source =this.textBox1 });
//将Cstudent的Name值绑定到textBox2的TextProperty属性,显示
///对象----->UI控件
this.textBox2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu });
}
}
}
- 代码分析
先为作为target的类添加依赖属性,这里依赖属性是通过注册方式来实现的。依赖属性具有binding数据源的机制,并且DependencyObject已实现了INotifyPropertyChanged,可以作为数据源(source),此时source与target可以实现双向通信。