在用户控件中获取工具提示以显示数据绑定文本并保持打开状态

问题描述 投票:1回答:1

我有一个用户控件,显示一个TextBox以及一个小帮助图标。

我的目标是有一个ToolTip弹出窗口,显示一些数据绑定文本,并在鼠标悬停在帮助图标上时保持打开状态。

因此,为此我在用户控件中创建了一个HelpText依赖项属性,允许我将帮助文本字符串绑定到用户控件。

所以,我的用户控件看起来像这样

<UserControl Name="textField" ...>
    <StackPanel Orientation="Horizontal">
        <TextBox Text="{Binding ElementName=textField,Path=Text}"/>
        <Image Source="{StaticResource Help.Icon}">
            <Image.ToolTip>
                <ToolTip Content="{Binding ElementName=textField,Path=HelpText}"/>
            </Image.ToolTip>
        </Image>
    </StackPanel>
</UserControl>

此代码确实显示了工具提示,但它是空的!此外,StaysOpen属性没有任何区别,因为工具提示在几秒钟后关闭。

有趣的是,当我直接在Image控件的ToolTip属性上设置相同的绑定时,绑定的文本会在工具提示弹出窗口中显示,但它仍然不会保持打开状态:

<Image Source="{StaticResource Help.Icon}" ToolTip="{Binding ElementName=textField,Path=HelpText}">

所以我的问题是:

  1. 为什么绑定到用户控件的HelpText依赖项属性在第一个代码示例中不起作用,但在第二个代码示例中是否有效?
  2. 如何让ToolTip保持开放状态,或者我如何使ToolTip保持开放并显示数据绑定文本?

谢谢!

wpf data-binding user-controls tooltip
1个回答
10
投票

ToolTips不是与XAML其余部分相同的VisualTree的一部分,因此DataContext不会以您期望的方式继承。

编写ToolTip="{Binding SomeProperty}"会自动将ToolTip的DataContext设置为SomeProperty,但是如果您构建自定义工具提示,则必须自己完成。

<ToolTip DataContext="{Binding PlacementTarget.DataContext, 
        RelativeSource={RelativeSource Self}}" ... />

这将把ToolTip的DataContext绑定到ToolTip所在的任何对象的DataContext

要完成你想要做的事情,你的<ToolTip>可能看起来像这样,因为PlacementTarget将是你的Image

<!-- Could also use something like Tag if DataContext is actually used -->
<Image DataContext="{Binding ElementName=textField, Path=HelpText}" 
       Source="{StaticResource Help.Icon}">
    <Image.ToolTip>
        <ToolTip Content="{Binding PlacementTarget.DataContext, 
            RelativeSource={RelativeSource Self}}"/>
    </Image.ToolTip>
</Image>

至于为什么它不会保持开放,我不是积极的,但可能是因为ToolTipService.ShowDuration属性默认为5秒,这可能会覆盖StaysOpen属性。

您可以尝试将其设置为更高的值,例如

<Image ToolTipService.ShowDuration="60000" ... />

或者你可以尝试this workaround使用Popup风格看起来像ToolTip而不是。代码可能看起来像这样:

<Popup PlacementTarget="{Binding ElementName=MyImage}" 
       IsOpen="{Binding IsMouseOver, ElementName=MyImage, Mode=OneWay}">
    <TextBlock Text="{Binding ElementName=textField, Path=HelpText}" />
</Popup>
© www.soinside.com 2019 - 2024. All rights reserved.