none
How to make a custom dependency property two way - bindable on the target side? RRS feed

  • Question

  • Hi,

    I would like to implement a property in a custom control that works like TextBox.Text, i.e. as response to some user action I want to change the value of the property, and I want this change to be propagated to a property of a business object that is bound to the control.

    However, when I put the binding into place and then change the value of the control's property, the new value replaces the binding and is not forwarded to the business object.

    How can I have my custom control update the value of the bound property without breaking the binding?
    Sunday, July 19, 2009 1:33 PM

Answers

  • When you define the property you can define the metadata in order the property is two way binding by default, for example:

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register(
             "MyProperty",
             typeof(int),
             typeof(Window1),
             new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    
    

    http://weblogs.asp.net/marianor/
    • Marked as answer by hbarck Thursday, July 23, 2009 7:55 AM
    Sunday, July 19, 2009 3:46 PM

All replies

  • When you define the property you can define the metadata in order the property is two way binding by default, for example:

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register(
             "MyProperty",
             typeof(int),
             typeof(Window1),
             new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    
    

    http://weblogs.asp.net/marianor/
    • Marked as answer by hbarck Thursday, July 23, 2009 7:55 AM
    Sunday, July 19, 2009 3:46 PM
  • Hi,

    I know this, but how do I set its value, then? If I just do SetValue(MyPropertyProperty,newvalue), the binding will break, i.e. the property will have the new value, but the source property will not get it, and the binding between MyProperty and the source property will be removed.
    Monday, July 20, 2009 7:02 AM
  • Hi,

    today I got around to trying it out, which I should have done in the first place... the problem I remembered wasn't there anymore, so I guess it just appears in certain situations, maybe if the property type is an object... with an integer, this works fine.
    Thursday, July 23, 2009 7:58 AM