mcr76
mcr76

Reputation: 116

How to find out if a dependency property is bound to a readonly property?

I defined an user control and a dependency property (called: Text). Now I want to know if the bound property of Text is readonly? (in code behind)

I did not find an entry in the BindingExpression.

Can anyone help me?

Upvotes: 1

Views: 601

Answers (1)

Spawn
Spawn

Reputation: 935

For example we can make something like this:

// create some control
var elem = new FrameworkElement();
// create context for control
elem.DataContext = new TestClass();
// create binding
var bind = elem.SetBinding(UIElement.AllowDropProperty, "ReadOnlyBool");
// we can resolve property
var pi = bind.ResolvedSource.GetType().GetProperty(bind.ResolvedSourcePropertyName);
// and check if it writeable
var isReadOnly = pi.CanWrite;

Not every BindingExpression has ResolvedSource and/or ResolvedSourcePropertyName, so, i suppose, it reason why we have not information about resolved property.

Context:

public class TestClass : DependencyObject
{
    public static readonly DependencyPropertyKey ReadOnlyBoolProperty =
        DependencyProperty.RegisterReadOnly("ReadOnlyBool", typeof (bool), typeof (TestClass),
            new PropertyMetadata());

    public bool ReadOnlyBool => (bool) GetValue(ReadOnlyBoolProperty.DependencyProperty);
}

Upvotes: 1

Related Questions