大多数的绑定操作都设置了Source和Path属性。Source属性用于确定绑定的对象,而Path属性确定对象中的属性。
很多人遇到 {Binding} 时都会很困惑 . {Binding} 乍看起来好像缺少可用信息。实际上不是这样的,现在我对此解释一下
如果你阅读过我的上一篇文章,你应该知道:在控件树的上层里可以设置 DataContext 属性,所以并不一定要设置 Source 属性。
现在 来 说说 Path. 当要绑定的是整个对象而不是其中的单个属性时, Path 是可以省略的。其中的一种情况是:当数据源是一个 string 类型并且仅仅绑定其本身时,可以省略 Path
例如:
<Window x:Class="Test.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="300" Width="300"
xmlns:c="clr-namespace:System;assembly=mscorlib"
>
<Window.Resources>
<c:String x:Key="helloString">Hello</c:String>
</Window.Resources>
<Border DataContext="{StaticResource helloString}">
<TextBlock Text="{Binding}"/>
</Border>
</Window>
另外一种使用{Binding}的情况是:将元素对应地绑定到对象的属性上:
<Window.Resources>
<local:GreekGod Name="Zeus" Description="Supreme God of the Olympians" RomanName="Jupiter" x:Key="zeus"/>
</Window.Resources>
<Border DataContext="{StaticResource zeus}">
<ContentControl Content="{Binding}"/>
</Border>
ContentControl并不知道如何显示GreekGod的数据,所以只会显示该对象的ToString()的值。这可不是我们希望的结果,为此需要使用DataTemplate:指定要显示的数据
<Window.Resources>
<c:String x:Key="helloString">Hello</c:String>
<local:GreekGod Name="Zeus" Description="Supreme God of the Olympians" RomanName="Jupiter" x:Key="zeus"/>
<DataTemplate x:Key="contentTemplate">
<DockPanel>
<TextBlock Foreground="RoyalBlue" Text="{Binding Path=Name}" />
<TextBlock Text=":" Margin="0,0,5,0" />
<TextBlock Foreground="Silver" Text="{Binding Path=Description}" />
</DockPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<Border BorderBrush="RoyalBlue" BorderThickness="2" Margin="25,25,25,0" Padding="5" DataContext="{StaticResource helloString}">
<TextBlock Text="{Binding}"/>
</Border>
<Border BorderBrush="RoyalBlue" BorderThickness="2" Margin="25" Padding="5" DataContext="{StaticResource zeus}">
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource contentTemplate}"/>
</Border>
</StackPanel>
</Window>
需要注意的是:DataContext对象会自动应用到模板化的对象里,所以{Binding}实际上已经被指定了数据源
原文地址:What does "{Binding}" mean?
译者注:Beatriz Costa写本时的winfx版本是BETA 1,现在已经不能使用了。我改动了部分代码。放在这里供大家下载