{Binding}详释 (WPF)

大多数的绑定操作都设置了SourcePath属性。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}实际上已经被指定了数据源

  EmptyBinding-718770.png.jpg

原文地址:What does "{Binding}" mean?

译者注:Beatriz Costa写本时的winfx版本是BETA 1,现在已经不能使用了。我改动了部分代码。放在这里供大家下载

代码下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值