Reynier Booysen Reynier Booysen - 10 months ago 88
C# Question

Attached Behavior property not being set by binding in UWP

I created a behavior class with a dependency property that I want to attach to a control in my view (XAML). I am using MVVM and I need to set this attached property by binding it to a property in my ViewModel, but it does not get set. Here is a simplified version of what I want to do:

Behavior Class:

public static class TestBehavior
public static readonly DependencyProperty SomeStringProperty =
DependencyProperty.Register("SomeString", typeof(string), typeof(TestBehavior), new PropertyMetadata(""));

public static string GetSomeString(DependencyObject o)
return (string)o.GetValue(SomeStringProperty);

public static void SetSomeString(DependencyObject o, string value)
o.SetValue(SomeStringProperty, value);



<TextBlock Text="{Binding ViewModelProperty}" local:TestBehavior.SomeString="{Binding ViewModelProperty}" />

The "Text" property of the TextBlock binds correctly, but the "SomeString" property of the behavior does not.

Interestingly - if I "hard code" the behavior property to a value it does get set. For example:

<TextBlock Text="{Binding TestValue}" local:TestBehavior.SomeString="Foo" /> <!-- This Works -->

Any ideas why the binding to the behavior property does not work?

Answer Source

What do you expect the attached behaviour to do?

Are you determining that the attached property is/isn't working by setting a breakpoint on the GetSomeString/SetSomeString methods? If so, this won't work with binding as the Get/Set methods aren't called when binding is used.

If you want to react when the attached property changes irrespective of whether it's via binding or not then use the PropertyChangedCallback of the PropertyMetadata specified in the Register call.