首页 > Windows开发 > 详细

WPF中使用相对资源来进行绑定,数据源是通过DataContext来指定的

时间:2016-01-09 06:15:53      阅读:1392      评论:0      收藏:0      [点我收藏+]

1. 最外层是Window是对象,Window的ItemsControl使用了ItemsTemplate,然后在ItemsTemplate中要绑定Language属性,

    而整个Window的数据源是通过DataContext来指定的,类型是自定义的WindowViewModel, 而Language就是WindowViewModel的一个属性

            在Window的构造函数中书写:

               this.DataContext = new WindowViewModel();

 

2.在ItemsTemplate中进行绑定,核心代码如下:

技术分享
1 <TabItem 
2       Header="{Binding DataContext.Language, RelativeSource={RelativeSource AncestorType=Window, AncestorLevel=1}
3                      }"  />
View Code

  其中注意:

        使用了相对资源  RelativeSource来引用Window的DataContext,所以 AncestorType指定类型是Window, 层次是1层,
        特别要注意的是:

              需要绑定的数据是WindowViewModel类型的,而相对资源指定的是Window元素,它是没有Language这个属性的,

      Language是WindowViewModel的属性,而在这里我们正好将WindowViewModel赋值给了Window的DataContext,

      所以在绑定时使用的Path应该是 DataContext.Language,其中DataContext是一定不能少写的

WPF中使用相对资源来进行绑定,数据源是通过DataContext来指定的

原文:http://www.cnblogs.com/tommy-huang/p/5115355.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!