您的位置:首页 > 其它

WPF程序设计指南: Binding(数据绑定)[下]

2010-12-21 14:20 393 查看
注:一下内容及代码基本来自Charles Petzold著,蔡学庸译,电子工业出版社出版的《Windows Presentation Foundation 程序设计指南》一书

引言:在上一篇WPF: Binding(数据绑定)[上]中所提到的Binding,都是使用ElementName Property来设置数据源的,这一篇将叙述如何通过Binding的另外两个属性:SourceRelativeSource来设定绑定源(注意:这三个属性只能设置一个,否则会冲突),以及“如何让数据可以当作绑定源”和“如何在格式化转换源数据”

1. Binding一个对象的静态字段或者静态属性

在前面的一篇文章:WPF:Resource中我们知道,获取一个类型的静态字段或者静态属性的时候,我们可以使用x:Static获得,但是当我们需要获取一个某一个对象的静态字段或者属性,这时候我们就需要用到绑定。

例如,System.Globalization命名空间中的DateTimeFormatInfo类型的DayNames属性(非静态),它返回一个字符串数组,是一周中每一天的名字。其中DateTimeFormatInfo类本身提供的一个静态属性:DateTimeFormatInfo.CurrentInfo,返回一个DateTimeFormatInfo类型的实例,表示当前计算机设置的文化的时间信息。
代码

<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
TextBlock.FontSize="12" >

<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<TextBlock Text="This TextBlock has a FontFamily of " />
<TextBlock Text="{Binding RelativeSource={RelativeSource self},
Path=FontFamily}" />
<TextBlock Text=" and a FontSize of " />
<TextBlock Text="{Binding RelativeSource={RelativeSource self},
Path=FontSize}" />
</StackPanel>

<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<TextBlock Text="This TextBlock is inside a StackPanel with " />
<TextBlock Text=
"{Binding RelativeSource={RelativeSource
AncestorType={x:Type StackPanel}},
Path=Orientation}" />

<TextBlock Text=" orientation" />
</StackPanel>

<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<TextBlock Text="The parent StackPanel has " />
<TextBlock Text=
"{Binding RelativeSource={RelativeSource
AncestorType={x:Type StackPanel}, AncestorLevel=2},
Path=Orientation}" />

<TextBlock Text=" orientation" />
</StackPanel>
</StackPanel>


代码说明:

  (1)第一个和第二个绑定分别获取当前TextBlock自己的字体类型和大小

(2)第二个绑定显示当前TextBlock所在的stackpanel的Orientation属性值

(3)第二个绑定显示当前TextBlock所在的stackpanel所在的stackpanel的Orientation属性值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: