如何在HierarchicalDataTemplate中绑定父级的DataContext

时间:2013-11-05 15:45:05

标签: wpf mvvm binding

我遇到的情况是我使用HierarchicalDataTemplate,其中大多数显示字段都绑定到此模板中表示的项目(就像您期望的那样),但我还需要一个BindingUserControl本身的数据上下文。我无法管理最后一点。

所以我现在有:

<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>

所以有问题的是,我想访问ProjectTreeView中的数据,但无法在此代码中访问它。我用RelativeSource尝试了各种各样的东西,但这不起作用。怎么办呢?

1 个答案:

答案 0 :(得分:2)

尝试:

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