【问题标题】:How to bind a property from code-behind while the rest are bound to DataContext?如何从代码隐藏中绑定一个属性,而其余的则绑定到 DataContext?
【发布时间】:2018-12-08 07:28:20
【问题描述】:

我的目标是将 XAML 中的元素属性绑定到类背后代码的属性,而 DataContext 仍然是 ViewModel。

原因是,我在 XAML 中只有一些 UI 修饰属性,这些属性不受 ViewModel 控制,而是由背后的代码控制。

所以基本上我搜索的是这样的:

<Element 
    Attribute = "{Binding ThatOneCodeBehind.WhateverProperty}"
    OtherAttribute1 = "{Binding StillDataContextSomething}" 
    OtherAttribute2 = "{Binding StillDataContextSomething}"
/>

Attribute="{Binding ThatOneCodeBehind:WhateverProperty}" 的正确绑定语法是什么?

【问题讨论】:

  • “ThatOneCodeBehind.WhateverProperty”是包含“元素”控件的主控件的 DependencyProperty 吗?
  • 给那个元素一个名字,你就可以从代码中访问它。例如:&lt;Element x:Name="Test" ... 来自代码:Test.Attribute = WhateverYouWant
  • 假设您所指的“代码背后”是一个窗口,确保无论什么属性是窗口类中的公共属性,并像{Binding WhateverProperty, RelativeSource={RelativeSource AncestorType=Window}}一样绑定。

标签: wpf xaml data-binding code-behind


【解决方案1】:

您的代码在某个 UIElement 中,比如说Window。所以给你的元素加上名字后面的代码并绑定到它。当然属性CodeBehindProperty 应该在那里定义。

<Window x:Name="_this">
    <TextBox Text="{Binding CodeBehindProperty, ElementName=_this}"/>
</Window>

另一种方法是找到定义类型的祖先:

<TextBox Text="{Binding CodeBehindProperty, RelativeSource={RelativeSource AncestorType=Window}}"/>

【讨论】:

  • Perfekt - 这正是我一直在寻找但没有正确解决的问题。非常感谢!也感谢其他评论分发者。
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 2019-06-07
  • 2011-07-04
  • 2013-10-17
  • 2016-09-05
  • 2013-07-25
  • 2021-10-24
  • 1970-01-01
相关资源
最近更新 更多