Custom WPF Binding

I have a custom MarkupExtension that simulates binding. It works well in normal assignments but 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

    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 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; }
            this.value = value;
            this.Source = value;

Since ProvideValue will return the Binding instance anyway.

From the documentation, it looks like the object must be freezable (so they can be shared between various interested parties)

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

why don't you

return Value

inside the ProvideValue??


You can bind to only DependencyProperty. make a dependency property for Value in your MyExtension Class!

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

Need Your Help

Security Program - Splitting Files

security file permissions architecture

How would you go about describing the architecture of a "system" that splits a sensitive file into smaller pieces on different servers in order to protect the file?

jquery and ASP.Net AJAX framework

c# javascript jquery ajax

I am developing using VSTS 2008 + C# + .Net 3.5 + ASP.Net. I am new to jQuery and ASP.Net AJAX framework. Suppose I need to use jQuery function (e.g. from jquery-1.3.2.js). I want to confirm that j...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.