emvoll emvoll - 1 month ago 9
C# Question

WPF Binding to UserControl´s DependencyProperty not working as expected

I have some strange problem with DependecyProperty-binding.
To keep the question simpler iĀ“ve created some dummy-control, that has the same unwanted behaviour

I have a UserControl, that has a DependencyProperty defined in code behind:

public static readonly DependencyProperty TestValueProperty = DependencyProperty.Register("TestValue", typeof(string), typeof(Test), new PropertyMetadata(default(string)));

public string TestValue
{
get { return (string)GetValue(TestValueProperty); }
set { SetValue(TestValueProperty, value); }
}


This property is used in XAML:

<Label Content="{Binding TestValue}" />


This control should be used in another control like this:

<views:Test TestValue="{Binding Settings.Setting123}" />


Settings
is defined in viewmodel as property.

But the content of
Settings.Setting123
is not visible in my usercontrolĀ“s label.

When writing some fixes value instead of the binding it works fine:

<views:Test TestValue="Test" />


But of course i do not want a fixed value, but the content of the bound object.
Any hint what is going wrong here?

Thanks in advance!

Answer

You didn't share enough code for anybody to recreate the issue, but reading between the lines, I'm guessing that Label is in your UserControl XAML. If TestValue is a property of your UserControl, this will probably work:

<Label Content="{Binding TestValue, RelativeSource={RelativeSource AncestorType=UserControl}}" />

However, one reason you might have done that (and had it semi-work, with literal strings) is if you made your UserControl its own DataContext. In that case, then the problem is that you made your UserControl its own DataContext. If you did that, that Binding on the bound one is being evaluated in the context of the UserControl, which does not have a Settings.Setting123 property.

What a control's DataContext means, is that when you have a Binding on one of the controls properties or inside its XAML, that's where the Binding goes to look for the property you bind to. You're explicitly telling it to look in the wrong place.

If you make your UserControl its own DataContext, you can't bind anything to it. That's why you shouldn't do that. It's like one of those machines that does nothing but unplug itself from the wall. Instead, use {RelativeSource AncestorType=UserControl} bindings as above inside the UserControl XAML.

I shouldn't have to guess. You claim you created a minimal verifiable example, but didn't bother sharing it. If you share it, we can solve your problem with confidence.