XAML里的Binding

含义:

将数据源绑定到XAML对象中。Binding两端分别是数据源(Source)和目标(Target)。

Binding的标记扩展:

<StackPanel>

<Slider x:Name="slider" Maximum="100" Minimum="0" Margin="5">Slider>

<TextBox x:Name="text" Text="{Binding Path=Value,ElementName=slider}" BorderBrush="Pink"/>

StackPanel>

结果视图:

XAML里的Binding_第1张图片

控制Binding数据流向的属性是Mode,Mode的取值

OneWay:Source影响Target,但是Target影响不到Source;

TwoWay:Source与Target相互影响

OneWayToSource:Target影响Source,Source却影响不到Target

OneTime:仅绑定一次,显示初始值

看下面一个例子:

<Canvas>

<ScrollBar Name="scrolBar" Height="20" Width="250" Orientation="Horizontal" Canvas.Left="130" Canvas.Top="50" Minimum="1" Maximum="100" SmallChange="1"/>

<Label Content="OneWay" Height="25" Name="lable1" Canvas.Left="120" Canvas.Top="100"/>

<TextBox Height="25" Text="{Binding ElementName=scrolBar,Path=Value,Mode=OneWay}" Canvas.Left="255" Canvas.Top="100" Width="125"/>

<Label Content="OneWayToSource" Height="25" Name="lable2" Canvas.Left="100" Canvas.Top="150"/>

<TextBox Height="25" Text="{Binding ElementName=scrolBar,Path=Value,Mode=OneWayToSource}" Canvas.Left="255" Canvas.Top="150" Width="125"/>

<Label Content="TwoWay" Height="25" Name="lable3" Canvas.Left="120" Canvas.Top="200"/>

<TextBox Height="25" Text="{Binding ElementName=scrolBar,Path=Value,Mode=TwoWay}" Canvas.Left="255" Canvas.Top="200" Width="125"/>

<Label Content="OneTime" Height="25" Name="lable4" Canvas.Left="120" Canvas.Top="250"/>

<TextBox Height="25" Text="{Binding ElementName=scrolBar,Path=Value,Mode=OneTime}" Canvas.Left="255" Canvas.Top="250" Width="125"/>

Canvas>

XAML里的Binding_第2张图片

Binding的路径:

      Binding的Path属性来指定源

  1. 把Binding关联在Binding源的属性上;

<StackPanel>

        <Slider x:Name="slider" Maximum="100" Minimum="0" Margin="5">Slider>

        <TextBox x:Name="text" BorderBrush="Pink"/>

StackPanel>

C#代码:

Binding binding = new Binding("Value") { Source = this.slider };

this.text.SetBinding(TextBox.TextProperty, binding);

  1. Binding还支持多级路径

你可能感兴趣的:(XAML)