zoukankan      html  css  js  c++  java
  • WPF中使用相对资源来进行绑定,数据源是通过DataContext来指定的

    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是一定不能少写的

  • 相关阅读:
    层模型--绝对定位(position:absolute)
    什么是层模型?
    浮动模型
    流动模型(二)
    插值方法
    CFS调度分析(内核版本:2.6.34)
    CRC检验
    ubuntu误删home目录
    随想
    Android——Activity生命周期
  • 原文地址:https://www.cnblogs.com/tommy-huang/p/5115355.html
Copyright © 2011-2022 走看看