书名:WPF专业编程指南
作者:李应保
出版社:电子工业出版社
出版时间:2010-01
ISBN:9787121100116
一、数据绑定扩展
- (Binding)
- Binding扩展专门在XAML中用作数据绑定,将在第11章中详细讨论WPF中的数据绑定。
二、例子
<Window x:Class="Yingbao.Chapter2.SimpleUIBanding.AppWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="绑定" Height="373" Width="337">
<StackPanel>
<ScrollBar Name="scroll" Orientation ="Horizontal " Margin
="24" Maximum ="100" LargeChange ="10" SmallChange ="1"/>
<Label Height ="30">OneWay:</Label>
<TextBox Name="scrollValue1" Height ="20" Width ="200"
HorizontalAlignment="Center" Text ="{Binding
ElementName=scroll, Path=Value, Mode=OneWay}"/>
- 使用Binding扩展,设定了Mode、Path,等等属性。
三、相对数据源扩展
- (RelativeSource)
- 在数据绑定时,有时候需要把目标对象绑定到和目标对象自身有相关关系的对象上,这时就需要用到相对数据源扩展。例如:
<Window x:Class="Yingbao.Chapter2.RelativeEx.AppWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="相对绑定" Height="100" Width="300">
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<TextBlock FontSize="20" Text="{Binding
RelativeSource={RelativeSource self}, Path=FontSize}"/>
<TextBlock Margin="10,1,1,5" FontSize="20" Text="{Binding
RelativeSource={RelativeSource AncestorType={x:Type
StackPanel}}, Path=Orientation}"/>
</StackPanel>
</Window>
-
在这个例子中,使用了两个相对数据源扩展,
第一个TextBlock的Text绑定到自身的字体大小上;
第二个TextBlock的Text则绑定到其父节点StackPanel的Orientation属性上。
这段XAML的运行结果如图2-5所示。
图2-5 使用相对数据源
