70

I would like to make it so that, as default, when I bind to one of my dependency properties the binding mode is two-way and update-trigger is property changed. Is there a way to do this?

Here is an example of one of my dependency properties:

public static readonly DependencyProperty BindableSelectionLengthProperty =
        DependencyProperty.Register(
        "BindableSelectionLength",
        typeof(int),
        typeof(ModdedTextBox),
        new PropertyMetadata(OnBindableSelectionLengthChanged));
Justin
  • 2,399
  • 4
  • 31
  • 50

2 Answers2

115

When registering the property, initialize your metadata with:

new FrameworkPropertyMetadata
{
    BindsTwoWayByDefault = true,
    DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
}
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • 3
    I was able to set BindsTwoWayByDefault by adding this to my example dp: new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnBindableSelectionStartChanged). However, I am still having trouble setting the UpdateSourceTrigger to PropertyChanged. – Justin Apr 18 '10 at 21:47
  • 1
    I modified my answer to show how to do it with an object initializer. Use that instead of a constructor. – Diego Mijelshon Apr 18 '10 at 23:19
  • @DiegoMijelshon is there a way to allow only OneWay Binding mode ? – eran otzap Aug 19 '13 at 14:46
  • Very Cool,I'm just hunting for implementing TwoWay mode by hand. – zionpi Apr 18 '14 at 06:50
  • @Justin `DefaultUpdateSourceTrigger= UpdateSourceTrigger.PropertyChanged` does the trick – WiiMaxx Jan 30 '15 at 14:39
  • 4
    Guess it's worth noting that it's not possible to change the default to any other mode than `TwoWay`. So `OneTime` and `OneWayToSource` are excluded. At least I didn't find a way. – r41n Nov 17 '16 at 10:25
23

In the Dependency Property declaration it would look like this:

public static readonly DependencyProperty IsExpandedProperty = 
        DependencyProperty.Register("IsExpanded", typeof(bool), typeof(Dock), 
        new FrameworkPropertyMetadata(true,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            OnIsExpandedChanged));

public bool IsExpanded
{
    get { return (bool)GetValue(IsExpandedProperty); }
    set { SetValue(IsExpandedProperty, value); }
}
marbel82
  • 925
  • 1
  • 18
  • 39
Paul Matovich
  • 1,496
  • 15
  • 20