Binding是Wpf的核心内容之一
1、下面是Binding基础的一个例子。
XAML:
<Grid>
<TextBox x:Name="myTextBox" Height="80" HorizontalAlignment="Left" VerticalAlignment="Top" Width="200"/>
<Button Height="23" HorizontalAlignment="Left" Margin="38,89,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">Button</Button>
</Grid>
C# Code
public partial class BindingTestxaml : Window
{
Customer cust;
public BindingTestxaml()
{
InitializeComponent();
BindingTest();
}
private void BindingTest()
{
//准备数据源
cust = new Customer();
// cust.Name = "Tom";
//准备Binding
Binding bind = new Binding();
bind.Source = cust;
bind.Path = new System.Windows.PropertyPath("Name");
//使用Binding连接数据源与Binding目标
BindingOperations.SetBinding(myTextBox, TextBox.TextProperty, bind);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
cust.Name += " Tom";
}
}
public class Customer:INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set
{
this.name = value;
//激发事件
if (PropertyChanged != null)
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
#region INotifyPropertyChanged 成员
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
当然上面的绑定也可以变成一句话的形式:如
//使用Binding连接数据源与Binding目标
BindingOperations.SetBinding(myTextBox, TextBox.TextProperty, new Binding("Name") { Source= cust =new Customer()});
2、没有Source的Binding——使用DataContext作为Binding的源,下面是一个简单的例子
先创建一个名为Sutdent的类,它有三个ID,Name,Age三个属性:
public class Student
{
public string ID{ get; set;}
public string Name { get; set; }
public string Age { get; set; }
}
然后XAML创建程序UI:
<StackPanel Background="LightBlue" Margin="0,118,0,0" HorizontalAlignment="Right" Width="201" Height="122" VerticalAlignment="Top">
<StackPanel.DataContext>
<local:Student ID="10" Name="Work Hard Work Smart" Age="30"/>
</StackPanel.DataContext>
<TextBox Height="23" HorizontalAlignment="Center" Margin="10" Name="textBox10" VerticalAlignment="Top" Text="{Binding Path=ID}" Width="164" />
<TextBox Height="23" HorizontalAlignment="Center" Margin="10" Name="textBox11" VerticalAlignment="Top" Text="{Binding Path=Name}" Width="164" />
<TextBox Height="23" HorizontalAlignment="Center" Name="textBox12" VerticalAlignment="Top" Text="{Binding Path=Age}" Width="164" />
</StackPanel>
三个TextBox的Text通过Binding获取值,Bindng指定了Path,没有指定Source。