I have a custom MarkupExtension that simulates binding. It works well in normal assignments but not when used in Style Setters, for example:
<Setter Property="Content" Value="{local:MyExtension}" />
results in 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 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’s the problem?!
Kind of guessing, but it’s likely because the XAML compiler has special built-in support for the
Bindingclass, allowing its usage in this scenario (and others). TheBindingclass is also aMarkupExtension, but unfortunately it seals its implementation ofProvideValue().That said, you might just get away with this:
Since
ProvideValuewill return theBindinginstance anyway.