May include but is not limited to: binding options, static and dynamic resources, element bindings, setting the correct binding mode and update mode, binding to nullable values
I think one of the biggest points in WPF is data binding. It’s incredibly easy to bind a form or a list to an object or to a collection of objects. You just set the container’s DataContext property to your custom object, set up the XAML markup and you have bound your data.
But the Binding class has so many properties you can set that it’s easy to get lost. I’ll show you some properties used in basic data binding scenarios:
- Mode: the binding mode to use. It has five potential values, which are:
- TwoWay: updates the target property or the property whenever either of them changed.
- OneWay: update the target property whenever the source property changed.
- OneTime: updates the target property only at startup, or when you change the underlying DataContext.
- OneWayToSource: updates the source property whenever the target property changed.
- Default: delegates the task to handle binding changes to the target properties target. User-editable properties usually have two-way bindings, others usually have one-way bindings. But exceptions occur.
- Path: the path of the property to bind to, such as TextBox.Text.
- StringFormat: when the target property is a string, you can set its format. It is like a Converter, but on a much more basic level.
- TargetNullValue: if you bind to a nullable value which happens to be null, you can specify another value to bind to. If you’d like to show a static text, like “Value is null”, you need to wrap it between parentheses.
- UpdateSourceTrigger: it defines the time to bind. The default value is LostFocus, which means that the property gets bound when the focus is lost (you navigate further). Other possible values are explicit (binding only occurs when you call it from code) or PropertyChanged, which updates the binding in the moment of a property change.
So that’s all you need to know about the Binding class for now. It’s worth knowing that you can bind elements together. It hasn’t got much sense, but for example, you can bind together a TextBox and a Slider. Then if you move the slider, your textbox will be updated – or if you type in text, the slider will jump to that position (of course if you set up the binding this way).