【问题标题】:WPF Binding with RelativeSource SelfWPF 与 RelativeSource Self 绑定
【发布时间】:2014-11-15 14:32:24
【问题描述】:

我对 whn 在绑定时使用 {RelativeSource Self} 感到困惑。以下三个绑定在我看来是一样的,其中 MyText 是我的视图模型中的一个属性。

<TextBlock Text = "{Binding Path=MyText RelativeSource{RelativeSource Self} }" />
<TextBlock Text = "{Binding MyText RelativeSource{RelativeSource Self} }" />
<TextBlock Text = "{Binding MyText }" />

我什么时候应该在绑定中使用 Self?谢谢。

【问题讨论】:

    标签: wpf binding self


    【解决方案1】:

    前两个是等效的,并且绑定到TextBlock 本身的MyText 属性。但是当然,它们不起作用,因为TextBlock 上没有MyText 属性。

    第三个绑定到当前DataContextMyText属性

    当您需要绑定到当前控件的属性时使用RelativeSource.Self

    【讨论】:

    • 感谢您的澄清。如果不指定,TextBlock 的 DataContext 应该和它的 parent 一样?
    • @Helic,是的。 DataContext 的值由子元素继承,除非显式替换。
    • 另外,如果我定义一个控件模板来替换控件的默认显示模板,那么 textblock 的数据上下文是什么?
    • @Helic,这取决于控件的实例化位置。控制模板对此没有任何改变。但无论如何,在大多数情况下,控件模板不应该尝试使用 DataContext。这就是 DataTemplates 的用途。
    猜你喜欢
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2012-09-07
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多