WPF custom binding

I have a custom MarkupExtension that mimics a binding. It works well in ordinary applications, but when used in Style Setters, for example:

<Setter Property="Content" Value="{local:MyExtension}" /> 

throws a XamlParseException:

 A 'Binding' cannot be set on the 'Value' property of type 'Setter'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject. 

This is an implementation of the extension:

 public class MyExtension : MarkupExtension { public MyExtension() { Value = 123; } public object Value { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { var binding = new Binding("Value") { Source = this, }; return binding.ProvideValue(serviceProvider); } } 

What a problem ?!

+1
source share
3 answers

It’s a kind of guessing, but this is probably because the XAML compiler has special built-in support for the Binding class, which allows it to be used in this scenario (and others). The Binding class is also MarkupExtension , but unfortunately it closes the implementation of ProvideValue() .

However, you can just get away from this:

 public class MyBinding : Binding { private object value; public object Value { get { return this.value; } set { this.value = value; this.Source = value; } } } 

Since ProvideValue will return an instance of Binding anyway.

+2
source

From the documentation, it seems the object should be frozen (so that they can be shared among various stakeholders)

http://msdn.microsoft.com/en-us/library/system.windows.setter.value.aspx

"Data binding and dynamic resources within an object are supported if the specified value is a Freezable object. See Binding Markup Extension and Dynamic Extension Markup Extension."

0
source

Why will not you

 return Value 

inside ProvideValue ??

yet

You can only bind to DependencyProperty . create the dependency property for Value in the MyExtension class!

 public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(Object), typeof(MyContentControl), new UIPropertyMetadata()); 
0
source

All Articles