How do I use RelativeSource
with WPF bindings and what are the different use-cases?
I created a library to simplify the binding syntax of WPF including making it easier to use RelativeSource. Here are some examples. Before:
{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
{Binding Path=Text, ElementName=MyTextBox}
After:
{BindTo PathToProperty}
{BindTo Ancestor.typeOfAncestor.PathToProperty}
{BindTo Template.PathToProperty}
{BindTo #MyTextBox.Text}
Here is an example of how method binding is simplified. Before:
// C# code
private ICommand _saveCommand;
public ICommand SaveCommand {
get {
if (_saveCommand == null) {
_saveCommand = new RelayCommand(x => this.SaveObject());
}
return _saveCommand;
}
}
private void SaveObject() {
// do something
}
// XAML
{Binding Path=SaveCommand}
After:
// C# code
private void SaveObject() {
// do something
}
// XAML
{BindTo SaveObject()}
You can find the library here: http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html
Note in the 'BEFORE' example that I use for method binding that code was already optimized by using RelayCommand
which last I checked is not a native part of WPF. Without that the 'BEFORE' example would have been even longer.