c# - WPF 用户控件的绑定(bind)问题

标签 c# wpf xaml binding user-controls

这就是我真正想要的。 UserControlTextBlock谁的Text属性绑定(bind)到 Prop UserControl 的属性(property). (这只是我实际问题的代表)

下面是我的 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作为

<userControl:ClientDetailsControl Prop="{Binding MyProp}" />

MyProp属性在 NewOrder.xaml.cs 中声明如下

public String MyProp { get { return "HELLO"; } }

当我运行这段代码时,出现以下错误:

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

它有效。但是,当我尝试绑定(bind) Prop UserControl 的属性(property)至 MyProp它不起作用。

我如何使它工作?

最佳答案

使用 RelativeSource像这样的属性:

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

关于c# - WPF 用户控件的绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31451083/

相关文章:

.net - 在 Silverlight 中工作时,您错过了哪些 .Net/WPF 功能?

c# - 将 C# 控制台应用程序设置为 Unicode 输出

javascript - 如何在标签中显示对象变量值

c# - 绘制可滚动 datagridview 时出现问题

WPF 数据网格 : How do you set the style of the first row only?

c# - 继承多个接口(interface)的类如何设置DataTemplate?

c# - UDP 广播/响应 - 避免类似 DDoS 的情况?

wpf - MVVM Light Toolkit - RelayCommands、DelegateCommands 和 ObservableObjects

c# - WPF - 在代码隐藏中更改样式

c# - WPF 动画不适用于 "fast"属性更改