WPF 用户控件的绑定问题

Binding issue with WPF user control(WPF 用户控件的绑定问题)
本文介绍了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 用户控件的绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)