Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to tell if the value of a DependencyProperty came from binding source or target?

I sometimes want to know if the value of a dependency property came from user input or from a change in the binding source. I have yet not found a clean way to determine this.

There are stuff like DependencyPropertyHelper but it does not help with this scenario as far as I can tell.

The scenario: <TextBox Text="{Binding Foo}" />

Find out if it was the binding source or target that updated Text last. Or something else, yes I'm aware of triggers, inheritance animations etc.

like image 217
Johan Larsson Avatar asked Oct 30 '22 00:10

Johan Larsson


1 Answers

Yes, you can get the binding expression associated with a Dependency Property and check its status:

BindingOperations.GetBindingExpressionBase(textBox, TextBox.TextProperty)?.Status == 
    BindingStatus.Active

You can combine it with DependencyPropertyHelper to check if the current source is BaseValueSource.Local.

ValueSource also has a property called IsExpression that is set to true when using a binding or any other expression, such as DynamicResource or TemplateBinding.

Finding whether the current value came from the source or the target is harder. AFAIK there's no better way than this:

<TextBox Text="{Binding Path=Foo, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}"
         SourceUpdated="OnSourceUpdated" TargetUpdated="OnTargetUpdated" />

Then you can hookup the handlers OnSourceUpdated and OnTargetUpdated and apply some logic. You can also created an attached property and update it for better encapsulation.

like image 157
Eli Arbel Avatar answered Nov 24 '22 00:11

Eli Arbel