我有一个用户控件,它显示一个 TextBox
以及一个小的帮助图标。
我的目标是有一个 ToolTip
弹出窗口,显示一些数据绑定(bind)文本并在鼠标悬停在帮助图标上时保持打开状态。
因此,为此,我在用户控件中创建了一个 HelpText 依赖属性,允许我将帮助文本字符串绑定(bind)到用户控件。
所以,我的用户控件看起来像这样
<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 属性上设置相同的绑定(bind)时,绑定(bind)的文本在工具提示弹出窗口中显示正常,但它仍然没有保持打开状态:
<Image Source="{StaticResource Help.Icon}" ToolTip="{Binding ElementName=textField,Path=HelpText}">
所以我的问题是:
- 为什么针对用户控件的 HelpText 依赖属性的绑定(bind)在第一个代码示例中不起作用但在第二个代码示例中起作用?
- 如何使
ToolTip
保持打开状态,或者更确切地说,如何使ToolTip
保持打开状态并显示数据绑定(bind)文本?
谢谢!
最佳答案
工具提示与 XAML 的其余部分不属于同一个 VisualTree,因此 DataContext
并没有像您期望的那样继承。
写作 ToolTip="{Binding SomeProperty}"
将自动设置工具提示的 DataContext
至 SomeProperty
,但是,如果您构建自定义工具提示,则必须自己执行此操作。
<ToolTip DataContext="{Binding PlacementTarget.DataContext,
RelativeSource={RelativeSource Self}}" ... />
这将绑定(bind)工具提示的 DataContext
到 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
属性(property)。
您可以尝试将其设置为更高的值,例如
<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>
关于wpf - 在用户控件中获取工具提示以显示数据绑定(bind)文本并保持打开状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14754813/