大多数的绑定操作都设置了Source和Path属性。Source属性用于确定绑定的对象,而Path属性确定对象中的属性。
很多人遇到{Binding}时都会很困惑. {Binding} 乍看起来好像缺少可用信息。实际上不是这样的,现在我对此解释一下
例如:
<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,现在已经不能使用了。我改动了部分代码。放在这里供大家下载