Wrong alignment of ContextMenu and Popup WPF controls on Windows 10

喜欢而已 提交于 2019-12-12 17:46:03

问题


It's really strange problem which I hope somebody knows how to solve. Situation:

  1. Our WPF project has a form on which we show context menus (ContextMenu control) and popups (Popup control) in response on some user actions. In most cases it happens on mouse click on some text block. Here is an example:

            popup = new Popup {
                Placement = PlacementMode.Relative,
                PlacementTarget = textBlock,
                StaysOpen = false
            }; 
    
            .   .   .   .   .
            //later on mouse click:
            popup.IsOpen = true;
    
  2. The popup must appear aligned to the top-left corner of its placement target (some text block in our example) and so - overlap it. And it works just well in all cases except Windows 10 machines which have tablet mode (like MS Surface Pro). In such environments our popups appear to the left side of the placement targets and so - do not overlap them.

As we discovered it happens because of the special Windows 10 option described in this article: http://www.isunshare.com/windows-10/show-context-menu-on-left-or-right-in-windows-10.html

This option is set to "Right-handed" by default (which is understandable) but I don't understand why it influences in such way on Popup control and why it happens even in Desktop mode.

It would be great to find a way to change this default behavior and make our Popup appear aligned to top-left corner of parent control in any case. Does anybody know how to do it?


回答1:


You can specify a PlacementRectangle:

<Border Width="300" Height="20" Background="Yellow">
  <Popup IsOpen="True" Placement="Left">
      <Popup.PlacementRectangle>
        <Rect X="0" Y="20" Width="0" Height="0" />
      </Popup.PlacementRectangle>
    <Border Width="100" Height="100" Background="Blue"></Border>
  </Popup>
</Border>

Which looks like this, even with right-handed tablet mode engaged:

The hack here is that the Y property is set to the correct height. If you have a fixed height popup, that might be fine. Otherwise you could try bing to the content's ActualHeight, but as Rect.Y is not a dependency property you'd need a converter from double to Rect for that purpose.



来源:https://stackoverflow.com/questions/38980616/wrong-alignment-of-contextmenu-and-popup-wpf-controls-on-windows-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!