views:

62

answers:

3

Binding to a Dependency Property is easy in code-behind. You just create a new System.Windows.Data.Binding object, and then call the target dependency object's SetBinding method.

But how do you do this when the property which we're binding is a CLR property and you can't provide a DependencyProperty argument to SetBinding?

EDIT: The object implements INotifyPropertyChanged, if that's relevant.

+2  A: 

Binding targets MUST be dependency properties! That's the only requirement for databinding to work!

Read more here:

rudigrobler
A: 

If I understand your question correctly you have a FrameworkElement that exposes a plain old ordinary property that isn't backed up as a Dependency property. However you would like to set it as the target of a binding.

First off getting TwoWay binding to work would be unlikely and in most cases impossible. However if you only want one way binding then you could create an attached property as a surrogate for the actual property.

Lets imagine I have a StatusDisplay framework element that has a string Message property that for some really dumb reason doesn't support Message as a dependency property.

public static StatusDisplaySurrogates
{
    public static string GetMessage(StatusDisplay element)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        return element.GetValue(MessageProperty) as string;
    }

    public static void SetMessage(StatusDisplay element, string value)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        element.SetValue(MessageProperty, value);
    }

    public static readonly DependencyProperty MessageProperty =
        DependencyProperty.RegisterAttached(
            "Message",
            typeof(string),
            typeof(StatusDisplay),
            new PropertyMetadata(null, OnMessagePropertyChanged));

    private static void OnMessagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        StatusDisplay source = d as StatusDisplay;
        source.Message = e.NewValue as String;
    }
}

Of course if the StatusDisplay control has its Message property modified directly for any reason the state of this surrogate will no longer match. Still that may not matter for your purposes.

AnthonyWJones
A: 

Wait. Are you trying to bind 2 CLR properties?? Let me say such thing is impossible to achieve in normal way. eg. no kind of hardcore hack that can make your whole application unstable. One side of binding MUST be DependencyProperty. Period.

Euphoric