是否有任何方法可以阻止WPF Popup在屏幕外重新定位?

Ric*_*ich 10 c# wpf multiple-monitors popup

是否有任何方法可以阻止WPF Popup在屏幕外重新定位?

我发现了这个老问题,但它没有得到正确答案.有没有办法做到这一点?如果有必要,我愿意将其子类化.谢谢.

Ric*_*key 5

正如安德烈指出的那样,这种行为在Popup控制范围内并且难以克服.如果您愿意做一些工作,可以通过调整弹出窗口内容到达屏幕边缘时进行调整和翻译.出于演示的目的,我们将专注于屏幕的左边缘.

如果我们有这样的XAML:

<Window ...
        LocationChanged="Window_LocationChanged"
        SizeChanged="Window_SizeChanged"
        >
    <Grid>
        <Rectangle Name="rectangle1" Width="100" Height="100" Fill="Blue"/>
        <Popup Name="popup1" PlacementTarget="{Binding ElementName=rectangle1}" IsOpen="True" Width="100" Height="100">
            <TextBlock Background="White" TextWrapping="Wrap" Width="100" Height="100">
                <TextBlock.Text>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</TextBlock.Text>
            </TextBlock>
        </Popup>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

和代码隐藏这样:

private void Window_LocationChanged(object sender, EventArgs e)
{
    RefreshPopupPosition();
}

private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
    RefreshPopupPosition();
}

private void RefreshPopupPosition()
{
    var upperLeft = rectangle1.PointToScreen(new Point(0, 100));
    var xOffset = Math.Min(0, upperLeft.X);
    popup1.Width = xOffset + 100;
    (popup1.Child as FrameworkElement).Margin = new Thickness(xOffset, 0, 0, 0);
    popup1.HorizontalOffset += 1;
    popup1.HorizontalOffset -= 1;
}
Run Code Online (Sandbox Code Playgroud)

然后通过计算Popup屏幕外的内容,我们可以减小内容的宽度并给它一个负边距,这样屏幕上的部分就会被剪切Popup到允许这样做的部分.

这将不得不扩展到处理屏幕的所有四个边缘和多个屏幕的可能性,但它表明该方法是可行的.