wpfIntroduction to WPF Data Binding


Syntax

  • {Binding PropertyName} is equivalent to {Binding Path=PropertyName}
  • {Binding Path=SomeProperty.SomeOtherProperty.YetAnotherProperty}
  • {Binding Path=SomeListProperty[1]}

Parameters

ParameterDetails
PathSpecifies the path to bind to. If unspecified, binds to the DataContext itself.
UpdateSourceTriggerSpecifies when the binding source has its value updated. Defaults to LostFocus. Most used value is PropertyChanged.
ModeTypically OneWay or TwoWay. If unspecified by the binding, it defaults to OneWay unless the binding target requests it to be TwoWay. An error occurs when TwoWay is used to bind to a readonly property, e.g. OneWay must be explicitly set when binding a readonly string property to TextBox.Text.
SourceAllows for using a StaticResource as a binding source instead of the current DataContext.
RelativeSourceAllows for using another XAML element as a binding source instead of the current DataContext.
ElementNameAllows for using a named XAML element as a binding source instead of the current DataContext.
FallbackValueIf the binding fails, this value is provided to the binding target.
TargetNullValueIf the binding source value is null, this value is provided to the binding target.
ConverterSpecifies the converter StaticResource that is used to convert the binding's value, e.g. convert a boolean to a Visibility enum item.
ConverterParameterSpecifies an optional parameter to be provided to the converter. This value must be static and cannot be bound.
StringFormatSpecifies a format string to be used when displaying the bound value.
Delay(WPF 4.5+) Specifies a Delay in milliseconds for the binding to update the BindingSource in the ViewModel. This must be used with Mode=TwoWay and UpdateSourceTrigger=PropertyChanged to take effect.

Remarks

UpdateSourceTrigger

By default, WPF updates the binding source when the control loses focus. However, if there is only one control that can get focus -- something that's common in examples -- you will need to specify UpdateSourceTrigger=PropertyChanged for the updates to work.

You will want want to use PropertyChanged as the trigger on many two-way bindings unless updating the binding source on every keystroke is costly or live data validation is undesirable.

Using LostFocus has an unfortunate side effect: pressing enter to submit a form using a button marked IsDefault does not update the property backing your binding, effectively undoing your changes. Fortunately, some workarounds exist.

Please also note that, unlike UWP, WPF (4.5+) also has the Delay property in bindings, wich might just be enough for some Bindings with local-only or simple minor intelligence settings, like some TextBox validations.