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

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

问题描述

下面是我想本质。
A 用户控件的TextBlock 文本属性绑定到的用户控件道具属性。 (这仅仅是一个重新$我的实际问题的对$ psentation)

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)

下面是部分我的用户控件 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 )我使用这个用户控件

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"; } }

当我运行这个code我得到以下错误:

When I run this code I get the following error:

BindingEx pression路径错误:'MyProp'属性不是'对象'发现
  ''ClientDetailsControl'(名称='')。 BindingEx pression:路径= MyProp;
  的DataItem ='ClientDetailsControl'(名称='');目标元素是
  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" />

它的工作原理。然而,当我尝试的道具属性绑定的用户控件 MyProp 它不工作。

It works. However, when I try to bind the Prop property of the UserControl to MyProp it doesnt work.

我如何使这项工作?

推荐答案

使用的 的RelativeSource 属性是这样的:

Use the RelativeSource property like this:

<userControl:ClientDetailsControl 
  Prop="{Binding MyProp,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"/>

这篇关于与WPF用户控件绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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