0

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?

Milen Grigorov
  • 332
  • 3
  • 13

1 Answers1

1

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); }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • @ mm8, Hi, My custom DP is set used default TwoWay binding, but when I set with mode=OneWay in Xaml, nothing happens when I Change binding property value. Can DP use as that way? – dellos Jan 18 '21 at 05:30