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

时间:2016-06-10 08:33:57

标签: wpf data-binding popup placement

我正在开发一个交互式图表,当用户点击数据点时,我会在其中显示包含更多信息的弹出窗口。到目前为止,此工作正常,这是弹出式定义:

<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"来实现水平居中,它具有固定的弹出宽度(宽度= 300)。对于垂直放置我有问题,弹出高度不固定,因为我在其中显示可变大小和宽高比的图像。因此,我尝试通过添加VerticalOffsetActualHeight设置为pupup的VerticalOffset="{Binding ActualHeight}"。不幸的是,这不起作用。关于我做错了什么以及如何实现目标的任何想法?

1 个答案:

答案 0 :(得分:1)

首先,你需要一个转换器:

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>

我希望它可以帮到你。