将 PopUp 放置在鼠标光标位置的顶部

Placing a PopUp to the top of the mouse-cursor position

我正在处理交互式图表,当用户单击数据时,我会在其中显示包含更多信息的弹出窗口-point.This 目前工作正常,这是弹出窗口定义:

<Popup IsOpen="{Binding PopupViewModel.IsOpen}"
        Placement="Mouse"
        HorizontalOffset="-150">
    <Popup.Resources>
        <DataTemplate DataType="{x:Type ViewModels:DataPointPopUpContentViewModel}">
            <Views:DataPointPopUpContentView/>
        </DataTemplate>
    </Popup.Resources>
    <Border BorderThickness="1" BorderBrush="Black" Background="White">
        <ContentPresenter Content="{Binding PopupViewModel}" />
    </Border>
</Popup>

当使用 Placement="Mouse" 时,弹出窗口的默认位置是在鼠标光标的右下角。但是,我希望将弹出窗口放置在鼠标光标的顶部边缘。如您所见,我通过设置 HorizontalOffset="-150" 实现了水平居中,它具有固定的弹出窗口宽度(Width=300)。对于垂直放置,我遇到了问题,即弹出高度不固定,因为我在其中显示了可变大小和纵横比的图像。因此,我尝试通过添加 VerticalOffset="{Binding ActualHeight}"VerticalOffset 设置为 pupup 的 ActualHeight。不幸的是,这不起作用。关于我做错了什么以及如何实现我的目标有什么想法吗?

首先你需要一个转换器:

public class MultiplyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is double && parameter is double)
        {
            return ((double)value) * ((double)parameter);
        }

        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

然后尝试将 VerticalOffset 属性 绑定到 Popup 子项的 ActualHeight

<Window.Resources>
    <local:MultiplyConverter x:Key="MultiplyConverter" />
    <sys:Double x:Key="Factor">-.5</sys:Double>
</Window.Resources>

<Popup IsOpen="{Binding PopupViewModel.IsOpen}"
        Placement="Mouse"
        HorizontalOffset="-150">
    <Popup.VerticalOffset>
        <Binding Path="Child.ActualHeight" RelativeSource="{RelativeSource Self}"
                    Converter="{StaticResource MultiplyConverter}" ConverterParameter="{StaticResource Factor}" />
    </Popup.VerticalOffset>


    <!-- popup content -->
</Popup>

希望对您有所帮助