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?