(1)为指定控件绑定:Content=”{Binding Value,ElementName=sth,Mode=Default}”, ElementName的值表示数据绑定操作的源,Binding后面的项(Value)表示要获取的元素的属性。
为一组控件绑定:DataContext=”{Binding ElementName=sth}”
<StackPanel Width="250" DataContext="{Binding ElementName=mySB}">
<Label Content="move the scroll"></Label>
<ScrollBar Orientation="Horizontal" Height="30" Name="mySB" Maximum="100" LargeChange="1" SmallChange="1"/>
<Label x:Name="labelSBThunl" Height="30" BorderBrush="Blue" BorderThickness="2" Content="{Binding Path=Value}"/>
<Button Content="click" Height="200" FontSize="{Binding Path=Value}"/>
</StackPanel>
DataContext绑定的是mySB,mySB移动时所有Content="{Binding Path=Value}"的数据都更改。
(2)使用IValueConverter进行数据转换
可以将数据绑定的值转换为其他格式。需要实现IValueConverter接口。
class MyDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double v = (double)value;
return (int)v;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
当源转换为目标时,会调用Convert()方法。这里是转换为int后返回。当值从目标传递会源时,调用ConvertBack()方法,这里直接返回value。
(3)在代码中建立数据绑定
将上面lable中的数据Content="{Binding Path=Value}"用代码绑定。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SetBindings();
}
private void SetBindings()
{
Binding b = new Binding();
b.Converter = new MyDoubleConverter();
b.Source = this.mySB;
b.Path = new PropertyPath("Value");
this.labelSBThunl.SetBinding(Label.ContentProperty, b);
}
}
SetBinding第一个参数指定进行绑定的类的名称,然后条用包含-Property后缀的实际属性。