如何从代码隐藏中绑定属性,而其余属性则绑定到 DataContext?

use*_*240 2 data-binding wpf xaml code-behind

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

原因是,我在 XAML 中有一些唯一的 UI 装饰属性,这些属性不是由 ViewModel 控制而是由后面的代码控制。

所以基本上我搜索类似的东西:

<Element 
    Attribute = "{Binding ThatOneCodeBehind.WhateverProperty}"
    OtherAttribute1 = "{Binding StillDataContextSomething}" 
    OtherAttribute2 = "{Binding StillDataContextSomething}"
/>
Run Code Online (Sandbox Code Playgroud)

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

Rek*_*ino 5

您背后的代码位于某个 UIElement 中,比如说Window. 因此,请为您的元素提供名称后面的代码并绑定到它。当然,属性CodeBehindProperty应该在那里定义。

<Window x:Name="_this">
    <TextBox Text="{Binding CodeBehindProperty, ElementName=_this}"/>
</Window>
Run Code Online (Sandbox Code Playgroud)

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

<TextBox Text="{Binding CodeBehindProperty, RelativeSource={RelativeSource AncestorType=Window}}"/>
Run Code Online (Sandbox Code Playgroud)