How do I bind to the parent's DataContext in a HierarchicalDataTemplate

南楼画角 提交于 2019-12-25 00:42:47

问题


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?


回答1:


Try :

   <DataTrigger Binding="{Binding Path=DataContext.SelectedStreet, RelativeSource={RelativeSource AncestorType=UserControl}}, UpdateSourceTrigger=PropertyChanged}" Value="Main Street">
         <Setter Property="FontWeight" Value="Bold" />
   </DataTrigger>


来源:https://stackoverflow.com/questions/19792926/how-do-i-bind-to-the-parents-datacontext-in-a-hierarchicaldatatemplate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!