Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the default binding mode of a dependency property?

I want to programmatically find out what the default binding mode of a property will be.

For example, if I check it against TextBox.TextProperty it should be BindingMode.TwoWay, but if it is ItemsControl.ItemsSourceProperty it should be BindingMode.OneWay.

I implemented a custom MarkupExtension and have gotten this far in my code so far:

public override object ProvideValue(IServiceProvider provider)
{
    var service = provider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;

    if (service != null)
    {
        var target = service.TargetObject as DependencyObject;
        var property = service.TargetProperty as DependencyProperty;

        // Not sure what to do with the target and propery here...
    }
}
like image 425
michael Avatar asked Dec 10 '13 20:12

michael


People also ask

How do I set default value for dependency property?

When you define a custom XAML dependency property, one of the things you do is specify the default value. You can do this by providing the default value directly: DependencyProperty. Register("MyProperty", propertyType, ownerType, new PropertyMetadata(defaultValue));

What is the default binding mode in WPF?

Default Data-binding It just defines which is the default binding mode for the control's property. In WPF different controls has different default data-binding modes. For example, TextBlock's Text property has one-way as default binding mode but a TextBox's Text property has a two-way binding mode.

How do you declare a dependency property?

Follow the steps given below to define custom dependency property in C#. Declare and register your dependency property with system call register. Provide the setter and getter for the property. Define an instance handler which will handle any changes that occur to that particular instance.

What is correct answer about the dependency property in WPF?

Dependency properties and the WPF property system extend property functionality by providing a type that backs a property, as an alternative to the standard pattern of backing a property with a private field. The name of this type is DependencyProperty.


1 Answers

Use DependencyProperty.GetMetadata on the DependencyObject. This will give you a PropertyMetadata value that will usually be an instance of FrameworkPropertyMetadata. Cast to that type if possible and check the value of BindsTwoWayByDefault.

For example:

var metadata = property.GetMetadata(target) as FrameworkPropertyMetadata;
if (metadata != null)
{
    var isTwoWay = metadata.BindsTwoWayByDefault;
}
like image 167
Jon Avatar answered Nov 14 '22 22:11

Jon