【问题标题】:Override ToolTip in WPF覆盖 WPF 中的工具提示
【发布时间】:2021-01-12 12:51:12
【问题描述】:

我希望将鼠标悬停在应用程序元素上时,工具提示不会显示在弹出窗口中,而是显示在应用程序的 TextBlock 中。我的知识使我能够以这种方式实现它。首先,我使资源提示不可见:

<Style x:Key="{x:Type ToolTip}" TargetType="ToolTip">
    <Setter Property="OverridesDefaultStyle" Value="true" />
    <Setter Property="HasDropShadow" Value="True" />
</Style>

接下来,我在每个需要提示的元素中编写提示文本和事件:

WPF:

<Button Content="Button"
    ToolTip="Tooltip text 1"
    ToolTipOpening="ToolTip"
    ToolTipClosing="ToolTip" />

<CheckBox Content="CheckBox"
    ToolTip="Tooltip text 2"
    ToolTipOpening="ToolTip"
    ToolTipClosing="ToolTip" />

(Similarly, other items)

C#:

public void ToolTip(object s, ToolTipEventArgs e)
{
    TextBlock.Text = 
        e.RoutedEvent == ToolTipService.ToolTipOpeningEvent 
        ? (s as FrameworkElement).ToolTip : string.Empty;    
}

它有效。但是是否可以不在元素中指明事件(ToolTipOpening="ToolTip"ToolTipClosing="ToolTip"),而是通过简单地在元素中指定提示(ToolTip="Tooltip text")来达到预期的效果?谢谢。

【问题讨论】:

  • Here 是如何在状态栏中显示工具提示。但是,如果没有工具提示,你为什么要使用工具提示呢?您可以创建附加行为来模仿工具提示行为(使用MouseEnter/MouseLeave)并通过您只需绑定的另一个附加属性公开当前值。

标签: c# wpf tooltip


【解决方案1】:

您不需要使用ToolTip,而是制作自己的可重用附加行为来模仿工具提示行为:

public class Behaviors
{
    public static TextBlock TextBlock { get; set; }

    public static string GetMyToolTip(DependencyObject obj) => (string)obj.GetValue(MyToolTipProperty);
    public static void SetMyToolTip(DependencyObject obj, string value) => obj.SetValue(MyToolTipProperty, value);

    public static readonly DependencyProperty MyToolTipProperty =
        DependencyProperty.RegisterAttached("MyToolTip", typeof(string), typeof(Behaviors), new FrameworkPropertyMetadata(null, (d, e) =>
        {
            var element = d as UIElement;
            element.MouseEnter += (s, a) => TextBlock.Text = e.NewValue.ToString();
            element.MouseLeave += (s, a) => TextBlock.Text = null;
        }));
}

那么你就可以简单的在xaml中使用了

<StackPanel>
    <TextBlock x:Name="textBlock" />
    <Button Content="1" local:Behaviors.MyToolTip="Button 1" />
    <Button Content="2" local:Behaviors.MyToolTip="Button 2" />
</StackPanel>

我不确定如何将工具提示传递给TextBoxnice。目前,您必须将静态 Behaviors.TextBlock 属性设置为该 TextBlock 明确:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Behaviors.TextBlock = textBlock;
    }
}

正在考虑 MVVM 方法,其中 DataContext 必须实现接口,或者可能使用另一个附加属性到 propagating instance 一直设置在窗口上,也许其他人可以改进这个想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    相关资源
    最近更新 更多