1. Introduction to Binding
WPF bindings enable better separation of business logic and UI by establishing a connection between the source data object and the UI control, implementing one-way or bidirectional change notifications. The usual pattern is to bind the target attribute (which is typically a XAML element control, and so on) to the data source (CLR object, ado.net Datasheet, XML data, and so on) by binding the object (which must be a dependent property) by the target object (which is usually a binding object instance). For example, we can bind TextBox1.Text to Personal.name.
In the following example, we can observe the following automatic behavior.
(1) If you click Btnset to modify the source object, you will find the target attribute textbox1. Text is automatically changed.
(2) Modify TextBox1. Text, click Btnget to find that the source object is automatically modified.
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.cs
class 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);
}
}