0

Consider this standard implementation of a DependencyProperty e.g. on a custom UserControl:

    public static readonly DependencyProperty MyStringProperty = DependencyProperty.Register(
        nameof(MyString), typeof(string), typeof(MyCustomControl), new PropertyMetadata(default(string)));

    public string MyString
    {
        get { return (string)GetValue(MyStringProperty); }
        set { SetValue(MyStringProperty, value); }
    }

This property could then be used in a binding like this:

    <MyCustomControl MyString="{Binding SomeDataContextProperty}"/>
    
    

If the DataContext of the MyCustomControl changes, then - due to the binding - the MyString property will be updated.

However, if I assign a value from code using e.g. MyString = "NewValue", changes will not be applied anymore, the binding is broken - or, erased as stated here (emphasis mine):

A local value might be set through the convenience of the property wrapper, which also equates to setting as an attribute or property element in XAML, or by a call to the SetValue method using a property of a specific instance. If you set a local value by using a binding or a static resource, these each act in the precedence as if a local value was set, and bindings or resource references are erased if a new local value is set.

I assumed setting the local value would change that instance's value without breaking/erasing the binding. But: once I change the value manually, all bindings are lost.

UPDATE: This post offers a solution to the above problem, but does not address the following issue:

In my actual use-case the binding used Mode=OneWay so the following issue didn't come up, but now I think: if I set the local value, it would be great, if that triggered the binding to update its source (SomeDataContextProperty in the example above).

Is this possible?

mike
  • 1,627
  • 1
  • 14
  • 37
  • See [Property functionality provided by a dependency property](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/properties/dependency-properties-overview?view=netdesktop-7.0#property-functionality-provided-by-a-dependency-property): *Bindings are treated as a local value, which means that if you set another local value, you'll eliminate the binding.* This means asking how to "*change local value without erasing bindings*" is pointless. You may however set the *effective value* of a dependency property. – Clemens Feb 22 '23 at 11:10
  • "*if I set the local value, it would be great, if that triggered the binding to update its source*" - that is what a TwoWay Binding does. And a TwoWay Binding is magically not replaced by setting a local value. You may even declare your MyString property in a way that it binds two-way by default. – Clemens Feb 22 '23 at 11:19

0 Answers0