首页 > 解决方案 > 通过相对源绑定在 Tooltip WPF 中不起作用

问题描述

我正在使用 Syncfusion 视觉风格。我正在尝试将 ToolTip 前景绑定在 StackPanel 内的 TextBlock 内,以显示 ToolTip 文本。但绑定在 TextBlock 中无法正常工作。

主窗口.xaml

<Grid>
   <CheckBox Grid.Row="5" Grid.Column="1" HorizontalAlignment="Center" Margin="0,4,10,0" VerticalAlignment="Center" IsChecked="{Binding AutoAdd, Mode=TwoWay}">
      <CheckBox.ToolTip>
         <StackPanel>
            <TextBlock Foreground="{Binding Path=Foreground, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type ToolTip}}}"   FontWeight="Bold" FontSize="14" Margin="0,0,0,5">Automatically Add To Path</TextBlock>
            <TextBlock Foreground="{Binding Path=Foreground, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type ToolTip}}}">
               If this path is associated with the primary configuration,
               <LineBreak />
               automatically add newly instantiated optical elements to the end of the path.
            </TextBlock>
            <Border BorderBrush="Silver" BorderThickness="0,1,0,0" Margin="0,8" />
            <WrapPanel>
               <Image Margin="0,0,5,0" />
               <TextBlock Foreground="{Binding Path=Foreground, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type ToolTip}}}" FontStyle="Italic">Press F1 for more help</TextBlock>
            </WrapPanel>
         </StackPanel>
      </CheckBox.ToolTip>
   </CheckBox>
</Grid>

有关此问题的任何其他解决方法。

问候,哈里·普拉萨德

标签: c#wpfdata-binding

解决方案


工具提示位于不同的数据上下文中,而不是直接位于可视化树中的控件,该控件似乎是其父级。因此,当您使用 relativesouce 搜索可视化树时,它什么也找不到。

您可以使用 PlacementTarget 来引用名义上它的父项 - 标记中的复选框

   "{Binding Path=PlacementTarget.PropertyName, RelativeSource={RelativeSource Self}}"

这里的 PropertyName 是您想要的任何属性。

如果您想在视图模型中添加一个属性,那可能是 DataContext.ViewModelProperty。

在这种情况下,我会尝试

Foreground="{Binding Path=PlacementTarget.Foreground, RelativeSource={RelativeSource Self}}"

根据您的使用情况,也许使用动态资源会更简单。


推荐阅读