WPF 用户控件的绑定问题 [英] Binding issue with WPF user control

查看:30
本文介绍了WPF 用户控件的绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要的.带有 TextBlockUserControl,其 Text 属性绑定到 UserControlProp 属性代码>.(这只是我实际问题的代表)

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" />

它有效.但是,当我尝试将 UserControlProp 属性绑定到 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 用户控件的绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆