问题描述
在一种情况下,我正在使用HierarchicalDataTemplate
,其中大多数显示字段都绑定到此模板中表示的项(如您期望的那样),但我还需要一个Binding
到数据上下文UserControl
本身.我无法管理这最后一点.
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.
所以我目前有:
<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
进行各种操作,但是那是行不通的.该怎么办?
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?
推荐答案
尝试:
<DataTrigger Binding="{Binding Path=DataContext.SelectedStreet, RelativeSource={RelativeSource AncestorType=UserControl}}, UpdateSourceTrigger=PropertyChanged}" Value="Main Street">
<Setter Property="FontWeight" Value="Bold" />
</DataTrigger>
这篇关于如何在HierarchicalDataTemplate中绑定到父级的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!