问题描述
这就是我想要的.带有 TextBlock
的 UserControl
,其 Text
属性绑定到 UserControl的
Prop
属性代码>.(这只是我实际问题的代表)
Here's what I essentially want.
A UserControl
with a TextBlock
whose Text
property is binded to the Prop
property of the UserControl
. (This is just a representation of my actual problem)
下面是我的 UserControl
的一部分(ClientDetailsControl.xaml
)
Below is a part of my UserControl
(ClientDetailsControl.xaml
)
<TextBlock Text="{Binding Prop}" />
接下来是 ClientDetailsControl.xaml.cs
public partial class ClientDetailsControl : UserControl
{
public static DependencyProperty PropProperty = DependencyProperty.Register("Prop", typeof(String), typeof(ClientDetailsControl));
public String Prop { get; set; }
public ClientDetailsControl()
{
InitializeComponent();
DataContext = this;
}
}
现在,在我的 WPF 主窗口(NewOrder.xaml
)中,我将这个 UserControl
用作
Now, In my main WPF window(NewOrder.xaml
) I am using this UserControl
as
<userControl:ClientDetailsControl Prop="{Binding MyProp}" />
MyProp
属性在 NewOrder.xaml.cs
public String MyProp { get { return "HELLO"; } }
当我运行此代码时,我收到以下错误:
When I run this code I get the following error:
BindingExpression 路径错误:在对象"上找不到MyProp"属性''ClientDetailsControl'(名称='')'.绑定表达式:路径=MyProp;DataItem='ClientDetailsControl' (Name='');目标元素是'ClientDetailsControl'(名称='');目标属性是道具"(类型'字符串')
BindingExpression path error: 'MyProp' property not found on 'object' ''ClientDetailsControl' (Name='')'. BindingExpression:Path=MyProp; DataItem='ClientDetailsControl' (Name=''); target element is 'ClientDetailsControl' (Name=''); target property is 'Prop' (type 'String')
当我简单地写
<userControl:ClientDetailsControl Prop="ABCD" />
它有效.但是,当我尝试将 UserControl
的 Prop
属性绑定到 MyProp
时,它不起作用.
It works. However, when I try to bind the Prop
property of the UserControl
to MyProp
it doesnt work.
我该如何进行这项工作??
How do I make this work??
推荐答案
使用 RelativeSource
属性如下:
Use the RelativeSource
property like this:
<userControl:ClientDetailsControl
Prop="{Binding MyProp,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"/>
这篇关于WPF 用户控件的绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!