我正在尝试将上下文菜单的可见性绑定到数据上下文的CanClose属性。 绑定适用于同一范围内的其他控件。
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Grid.Margin>
<Thickness Left="0" Top="0" Right="{StaticResource LBFTabMargin}"
Bottom="0" />
</Grid.Margin>
<Border Background="LightGray" BorderBrush="DarkGray" BorderThickness="1" x:Name="ForegroundBorder" />
<Grid>
<Grid Margin="{StaticResource LBFSmallThickness}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Foreground="{DynamicResource LBFTabTextBrush}"
FontWeight="SemiBold"
Margin="{StaticResource LBFSmallThickness}" MaxWidth="300"
VerticalAlignment="Center"
Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem} }, Path=Content.DataContext.TabHeader}"
ToolTipService.ToolTip="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem} }, Path=Content.DataContext.TabToolTip}">
<TextBlock.ContextMenu >
<ContextMenu Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Content.DataContext.CanClose,Converter={StaticResource VisibilityConverter}}">
<MenuItem Header="Luk alle"/>
<MenuItem Header="Luk alle, undtagen denne"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
<Button Width="15" Height="15"
Style="{StaticResource CloseButtonStyle}"
Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Content.DataContext.CanClose,Converter={StaticResource VisibilityConverter}}"
Grid.Column="1" IsHitTestVisible="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<infrastructure:CloseTabbedViewAction />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</Grid>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="ForegroundBorder" Property="Background" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我想绑定失败是因为上下文菜单不在可视化树中。我正在使用snoop来检查它。
答案 0 :(得分:1)
你是对的,上下文菜单不是可视化树的一部分。它们不会继承与它们所属的控件相同的源以进行绑定。处理此问题的方法是绑定到ContextMenu本身的放置目标。 所以试试这个:
<TextBlock.ContextMenu >
<ContextMenu Visibility="{Binding PlacementTarget.DataContext.CanClose, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Luk alle"/>
<MenuItem Header="Luk alle, undtagen denne"/>
</ContextMenu>
</TextBlock.ContextMenu>