Binding issue with WPF user control

回眸只為那壹抹淺笑 提交于 2019-12-20 02:08:28

问题


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)

Below is a part of my UserControl (ClientDetailsControl.xaml)

<TextBlock Text="{Binding Prop}" />

Next is the 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;
    }
}

Now, In my main WPF window(NewOrder.xaml) I am using this UserControl as

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

The MyProp property is declared as follows in the NewOrder.xaml.cs

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

When I run this code I get the following error:

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')

When I simply write

<userControl:ClientDetailsControl Prop="ABCD" />

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??


回答1:


Use the RelativeSource property like this:

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



回答2:


The reason it doesn't work is that binding paths are relative to the DataContext, not to the (parent) control.

This is why you can fix this by setting the RelativeSource; in that case the binding path uses the RelativeSource as the starting point of finding the property.

Another way to solve it is by naming the parent and setting the ElementName of the binding.

The MVVM way of doing this is adding a property to a ViewModel class, set the parent control's DataContext to an instance of the ViewModel and binding both the parent control and the client control to that property.



来源:https://stackoverflow.com/questions/31451083/binding-issue-with-wpf-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!