Search code examples
c#.netwpfc#-4.0

Multiple RelativeSource


I have a need in a DataTemplate to have my binding going to potentially 2 different types of RelativeSource ie something like this:

AllowDrop={Binding RelativeSource={RelativeSource AncestorType={x:Type Label} or AncestorType={x:Type TextBox}}, Path=AllowDrop}

In this case the relativeSource will look up the tree and find the first ancestor of type Label or TextBlock. Now I know what you're all going to say, "Why the heck to you want to do something stupid like that for??" Fair question, I'm glad you asked :-) The reason is that I am using the WPFish grid from syncfusion. I say WPFish because whoever wrote it didn't have a clear understanding of how WPF should work and it requires quite a few hacks to get it to work as it should. One of the hacks I need to set AllowDrop of a ContentControl in my template to be the same as the AllowDrop property on their grid. Normally this would be a fairly simple matter of just binding with a RelativeSource type of their grid, but they have 2 grids. One is called GridControl and the other GridDataControl. So I need to search up the tree to find the first control of type GridControl or GridDataControl and grab the AllowDrop property from that.

Thanks in advance, Michael


Solution

  • Use a Binding Converter and bind to the element itself and then walk the visual tree in the binding converter to find the element you want.....uuugggglllyyy!!

    {Binding Path=., RelativeSource={RelativeSource Self}, Converter={StaticResource findTheCorrectParentConverter}}

    and some code in your converter like so:

    DependencyObject parent = VisualTreeHelper.GetParent(item);
    while(!(parent is TextBox|| parent is Label)){
       parent = VisualTreeHelper.GetParent(parent);
    }
    
    if (parent != null){
       //do some stuff with your stuff.
    }