工具提示或类似的东西在WPF中随光标移动

本文关键字:WPF 光标 移动 工具提示 | 更新日期: 2023-09-27 18:09:50

是否有可能移动一个Tooltip或类似的东西,当鼠标在一个特定的控制?

我尝试了TextBlock,但Margin属性不工作。

    private TextBlock tooltip = new TextBlock();
    private void imgRoom_MouseEnter(object sender, MouseEventArgs e)
    {           
        Point position = e.GetPosition((IInputElement)sender);
        tooltip.Visibility = System.Windows.Visibility.Visible; 
        tooltip.Margin = new Thickness(position.X, position.Y, 0, 0);           
        tooltip.Width = 100;
        tooltip.Height = 100;
        tooltip.Background = new SolidColorBrush(Colors.Red);
    }
    private void imgRoom_MouseMove(object sender, MouseEventArgs e)
    {
        Point position = e.GetPosition((IInputElement)sender);
        tooltip.Margin = new Thickness(position.X, position.Y, 0, 0);
    }

工具提示或类似的东西在WPF中随光标移动

你可以使用一个弹出窗口和一些简单的属性来实现这个效果。从窗口代码…

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
  <Grid>
    <Rectangle Name="rect" Margin="50,50,0,0" Width="100" Height="100" Fill="LightBlue" MouseMove="Rectangle_MouseMove" MouseLeave="Rectangle_MouseLeave" />
    <Popup Name="floatingTip" AllowsTransparency="True" Placement="Relative" PlacementTarget="{Binding ElementName=rect}">
      <TextBlock>Look At Me</TextBlock>
    </Popup>
  </Grid>
</Window>

后面的代码是这样的

...
private void Rectangle_MouseMove(object sender, MouseEventArgs e)
{
  if (!floatingTip.IsOpen) { floatingTip.IsOpen = true; }
  Point currentPos = e.GetPosition(rect);
  // The + 20 part is so your mouse pointer doesn't overlap.
  floatingTip.HorizontalOffset = currentPos.X + 20;
  floatingTip.VerticalOffset = currentPos.Y;
}
private void Rectangle_MouseLeave(object sender, MouseEventArgs e)
{
  floatingTip.IsOpen = false;
}
...

从XAML中你可以看到弹出框的位置是相对于矩形的。当您将鼠标移到矩形上时,它就会变得可见,并且随着鼠标的移动,它的位置也会更新。当然,这是一个非常基本的解决方案,但有一些小的调整,处理事件,如'MouseEnter'和属性调整,你可以拿出一些真正整洁的效果。

我不知道这是否是最佳实践,或者它是否表现良好,但您可以使用Adorner

我之前已经创建了一个概念验证,但还没有在生产场景中使用它。该装饰器可用于创建如下内容(工具提示),或自定义鼠标光标或拖放目标图标。

如果装饰器不需要命中测试,并且可能直接出现在鼠标位置下,请确保设置IsHitTestVisible = false

完全阅读adorners的描述:

常用的装饰器应用包括:

  • 为元素添加功能句柄,使用户能够以某种方式操作元素(调整大小,旋转,重新定位等)。
  • 提供视觉反馈,以指示各种状态,或响应各种事件。
  • 在元素上叠加视觉装饰
  • 可视遮罩或覆盖部分或全部元素

这将使工具提示随着鼠标光标移动。

    private void OnMouseMoveHandler(object sender, MouseEventArgs args)
    {
        if ((sender as FrameworkElement).ToolTip == null)
            (sender as FrameworkElement).ToolTip = new ToolTip() { Placement = PlacementMode.Relative };
        double x = args.GetPosition((sender as FrameworkElement)).X;
        double y = args.GetPosition((sender as FrameworkElement)).Y;
        var tip = ((sender as FrameworkElement).ToolTip as ToolTip);
        tip.Content = tooltip_text;
        tip.HorizontalOffset = x + 10;
        tip.VerticalOffset = y + 10;
    }