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

Cla*_*sen 1 data-binding wpf user-controls tooltip

我有一个用户控件,显示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>
Run Code Online (Sandbox Code Playgroud)

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

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

<Image Source="{StaticResource Help.Icon}" ToolTip="{Binding ElementName=textField,Path=HelpText}">
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

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

谢谢!

Rac*_*hel 10

DataContext不是与XAML的其余部分相同的VisualTree的一部分,因此ToolTip="{Binding SomeProperty}"不会以您期望的方式继承.

写作DataContext将自动设置工具提示的SomePropertyDataContext,但是如果你建立一个自定义的工具提示你必须自己做.

<ToolTip DataContext="{Binding PlacementTarget.DataContext, 
        RelativeSource={RelativeSource Self}}" ... />
Run Code Online (Sandbox Code Playgroud)

这会将ToolTip绑定到ToolTip DataContext所在<ToolTip>的任何对象.

为了完成你想要做的事情,你PlacementTarget可能会看起来像这样,因为它Image会是你的StaysOpen:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

至于为什么它不会保持打开,我不是肯定的,但可能是因为ToolTipService.ShowDuration属性默认为5秒,这可能会覆盖该Popup属性.

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

<Image ToolTipService.ShowDuration="60000" ... />
Run Code Online (Sandbox Code Playgroud)

或者你可以尝试这种解决方法使用的ToolTip风格的,看起来像一个DataContext代替.代码可能看起来像这样:

<Popup PlacementTarget="{Binding ElementName=MyImage}" 
       IsOpen="{Binding IsMouseOver, ElementName=MyImage, Mode=OneWay}">
    <TextBlock Text="{Binding ElementName=textField, Path=HelpText}" />
</Popup>
Run Code Online (Sandbox Code Playgroud)