Search code examples
wpfbindingmultibinding

How can I convert a control that is already bound to multibinding


Let's say I have a FrameworkElement that is already bound to a converter in the XAML. Programmatically, I wish to append a binding to the existing binding at runtime - for instance in the control's loaded event, effectively making it a multibinding.

How does one go about acquiring the existing binding on (for example) the Visibility property.


Solution

  • You might do something like this:

    var oldBinding = BindingOperations.GetBinding(element, UIElement.VisibilityProperty);
    
    var newBinding = new MultiBinding { Converter = ... };
    
    var firstBinding = new Binding
    {
        Path = oldBinding.Path,
        Source = oldBinding.Source // or RelativeSource or ElementName
    };
    
    var secondBinding = new Binding
    {
        ...
    };
    
    newBinding.Bindings.Add(firstBinding);
    newBinding.Bindings.Add(secondBinding);
    
    BindingOperations.SetBinding(element, UIElement.VisibilityProperty, newBinding);