首页 / 软件开发 / .NET编程技术 / WPF学习笔记 - 8. Binding (1)
WPF学习笔记 - 8. Binding (1)2010-10-11 rainsts.net yuhen1. 绑定简介WPF 绑定可以在源数据对象和 UI 控件间建立联系,实现单向或双向变更通知,以此实现更好的业务逻辑和 UI 的分离。通常的模式是: 将目标对象(通常是XAML元素控件等)的目标属性(必须是依赖属性)通过绑定对象(Binding对象实例)绑定到数据源(CLR对象、ADO.NET 数据表、XML数据等)。比如我们可以将 TextBox1.Text 绑定到 Personal.Name。下面的例子中,我们可以观察到如下自动行为。(1) 单击 btnSet 修改源对象,会发现目标属性 textbox1.Text 自动变更。(2) 修改 textbox1.Text,单击 btnGet 会发现源对象被自动修改。Window.xaml<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="276" Width="360" WindowStartupLocation="CenterScreen">
<Grid>
<StackPanel>
<TextBox x:Name="textbox1" />
<Button x:Name="btnGet" Content="Get Name" Click="buttonClick" />
<Button x:Name="btnSet" Content="Set Name" Click="buttonClick" />
</StackPanel>
</Grid>
</Window>
Windows.xaml.csclass MyData : DependencyObject
{
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(MyData),
new UIPropertyMetadata("Hello, World!"));
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
}
public partial class Window1 : Window
{
MyData data;
public Window1()
{
InitializeComponent();
data = new MyData();
var binding = new Binding("Name") { Source = data };
this.textbox1.SetBinding(TextBox.TextProperty, binding);
}
private void buttonClick(object sender, RoutedEventArgs e)
{
if (sender == btnSet)
data.Name = DateTime.Now.ToString();
else
MessageBox.Show(data.Name);
}
}