Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom WPF Binding

Tags:

c#

wpf

xaml

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?!

like image 660
tech-man Avatar asked Dec 17 '25 20:12

tech-man


1 Answers

Kind of guessing, but it's likely because the XAML compiler has special built-in support for the Binding class, allowing its usage in this scenario (and others). The Binding class is also a MarkupExtension, but unfortunately it seals its implementation of ProvideValue().

That said, you might just get away with 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 the Binding instance anyway.

like image 134
Kent Boogaart Avatar answered Dec 19 '25 10:12

Kent Boogaart