0

I have a situation in which I am using a HierarchicalDataTemplate in which most display fields are bound to the items represented in this template (like you'd expect), but I also need one Binding to the data context of the UserControl itself. I fail to manage this last bit.

So I currently have:

<UserControl x:Class="MyProject.ProjectTreeView">

<UserControl.Resources>    
    <HierarchicalDataTemplate DataType="{x:Type StreetViewModel}" 
                              ItemsSource="{Binding Houses}">   

        <!-- This Binding works fine (binds to local:StreetViewModel.Street.StreetName) -->             
        <TextBlock Text="{Binding Street.StreetName}">
            <TextBlock.Style>
                <Style TargetType="{x:Type TextBlock}">
                    <Style.Triggers>
                         <!-- THIS BINDING DOESN'T WORK (I want it to bind to local:ProjectTreeView.SelectedStreet) -->
                        <DataTrigger Binding="{Binding Path=SelectedStreet, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}" Value="Main Street">
                            <Setter Property="FontWeight" Value="Bold" />
                        </DataTrigger>
                        <!-- This one works again (binds to local:StreetViewModel.Street.ConstructionWorkGoingOn) -->
                        <DataTrigger Binding="{Binding Street.ConstructionWorkGoingOn, UpdateSourceTrigger=PropertyChanged}"  Value="true">
                            <Setter Property="Foreground" Value="Red" />
                        </DataTrigger>
                   </Style.Triggers>
               </Style>
           </TextBlock.Style>
       </TextBlock>
   </HierarchicalDataTemplate>

So the problematic thing is that I want to access data in ProjectTreeView but can't reach it within this code. I've tried all sort of things with RelativeSource but that doesn't work. How can this be done?

Yellow
  • 3,955
  • 6
  • 45
  • 74
  • Did you try RelativeSource binding with AncestorType UserControl? `{Binding Path=SelectedStreet, RelativeSource=RelativeSource AncestorType=UserControl, AncestorLevel=1}, UpdateSourceTrigger=PropertyChanged}"` – Suresh Nov 05 '13 at 15:57
  • Almost, for some reason it still needs `...Path=DataContext.SelectedStreet...`, and then it works (see answer by @eran otzap). – Yellow Nov 05 '13 at 16:07

1 Answers1

2

Try :

   <DataTrigger Binding="{Binding Path=DataContext.SelectedStreet, RelativeSource={RelativeSource AncestorType=UserControl}}, UpdateSourceTrigger=PropertyChanged}" Value="Main Street">
         <Setter Property="FontWeight" Value="Bold" />
   </DataTrigger>
eran otzap
  • 12,293
  • 20
  • 84
  • 139