How do I use WPF bindings with RelativeSource?

前端 未结 13 1955
执念已碎
执念已碎 2020-11-22 03:00

How do I use RelativeSource with WPF bindings and what are the different use-cases?

13条回答
  •  囚心锁ツ
    2020-11-22 03:50

    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.

提交回复
热议问题