Ejemplo n.º 1
0
        private static void Popup_Opened(object sender, EventArgs e)
        {
            var popup = (Popup)sender;

            if (popup.TemplatedParent is MenuItem menuItem)
            {
                var topLine = GetTopLine(menuItem);
                if (topLine == null)
                {
                    return;
                }

                topLine.HorizontalAlignment = HorizontalAlignment.Left;
                topLine.Width  = menuItem.ActualWidth;
                topLine.Margin = new Thickness();

                var positionLeftTop     = menuItem.PointToScreen(new Point());
                var positionRightBottom = menuItem.PointToScreen(new Point(menuItem.ActualWidth, menuItem.ActualHeight));
                ScreenHelper.FindMonitorRectsFromPoint(InteropMethods.GetCursorPos(), out _, out var workAreaRect);
                var panel = VisualHelper.GetParent <Panel>(topLine);

                if (positionLeftTop.X < 0)
                {
                    topLine.Margin = new Thickness(positionLeftTop.X - panel.Margin.Left, 0, 0, 0);
                }
                else if (positionLeftTop.X + panel.ActualWidth > workAreaRect.Right)
                {
                    var overflowWidth = positionRightBottom.X - workAreaRect.Right;
                    if (overflowWidth > 0)
                    {
                        topLine.Width -= overflowWidth + panel.Margin.Right;
                    }
                    topLine.HorizontalAlignment = HorizontalAlignment.Left;
                    topLine.Margin = new Thickness(positionLeftTop.X + panel.ActualWidth - workAreaRect.Right + panel.Margin.Right, 0, 0, 0);
                }

                if (positionRightBottom.Y > workAreaRect.Bottom)
                {
                    topLine.Width = 0;
                    topLine.HorizontalAlignment = HorizontalAlignment.Stretch;
                    topLine.Margin = new Thickness();
                }
            }
        }