Search code examples
c#wpfdata-binding

Implementation of one way dependancy property


I am developing a custom User Control using WPF. I have registered DependancyProperty but I want to make it only OneWay binding. Is it possible to do it? Here is what I have:

public static readonly DependencyProperty CustomPrProperty =
        DependencyProperty.Register(
            "CustomPr",
            typeof(string),
            typeof(CustomView),
            new FrameworkPropertyMetadata(string.Empty, OnDependencyPropertyChanged));

This way when someone use the User Control, he can make it OneWay, OneWayToSource and TwoWay. How can I make it read only property?


Solution

  • You can set the BindsTwoWayByDefault property of the FrameworkPropertyMetadata to specify that the property binds two-way by default. The mode can still be changed by setting the Mode property of an individual binding to something else than TwoWay.

    To create a read-only dependency property that cannot be set, you should use the RegisterReadOnly method:

    internal static readonly DependencyPropertyKey CustomPrKey = DependencyProperty.RegisterReadOnly(
     "CustomPr",
     typeof(string),
     typeof(CustomView),
     new PropertyMetadata(string.Empty)
    );
    
    public static readonly DependencyProperty CustomPrProperty = CustomPrKey.DependencyProperty;
    
    public string CustomPr
    {
        get { return (string)GetValue(CustomPrProperty); }
    }