[英]Strange behavior of ContextMenu: placement “mirrored”
使用ContextMenu時,我面臨一個非常奇怪的行為(至少對我而言)。 這是簡化的xaml(MainWindow.xaml):
<Window x:Class="ContextMenuTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="500"
Height="300">
<Button Content="Do this" Height="25" Width="80" ContextMenuService.Placement="Right">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Do this" />
<MenuItem Header="Do that" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</Window>
使用此xaml,右鍵單擊該按鈕可獲得的預期結果是位於該按鈕右側的ContextMenu。 但是結果是:
http://i.stack.imgur.com/pSd0Q.png
of the button. 因此,ContextMenu奇怪地位於按鈕的 。 我還嘗試將ContextMenuService.Placement
屬性設置為Left
, Top
和Bottom
。 結果是:
Left
-> ContextMenu位於按鈕的 。 Top
-> ContextMenu放置在按鈕的 。 ) (不是 ) Bottom
-> ContextMenu放置在按鈕的 (而不是 ) (that is, the origin of the coordinate system is at the top-right of the window, not top-left). 在我看來,坐標系是 (也就是說,坐標系的原點位於窗口的右上角,而不是左上角)。 我根本不知道為什么。 我需要幫助將ContextMenu放置在按鈕的左下角。
(PS:此示例項目與Visual Studio 2013創建的默認項目相同,除了MainWindow.xaml。)
) found the solution. 好的,我終於(是, )找到了解決方案。 問題可能與此處所述的同構: WPF彈出彈出式
所以我寫了一個行為:
namespace Test {
public class WorkaroundForTheBugOfPopupBehavior : Behavior<FrameworkElement> {
private static readonly FieldInfo _menuDropAlignmentField;
static WorkaroundForTheBugOfContextMenuBehavior() {
_menuDropAlignmentField = typeof(SystemParameters).GetField("_menuDropAlignment", BindingFlags.NonPublic | BindingFlags.Static);
System.Diagnostics.Debug.Assert(_menuDropAlignmentField != null);
EnsureStandardPopupAlignment();
SystemParameters.StaticPropertyChanged += OnStaticPropertyChanged;
}
private static void EnsureStandardPopupAlignment() {
if (SystemParameters.MenuDropAlignment && _menuDropAlignmentField != null) {
_menuDropAlignmentField.SetValue(null, false);
}
}
private static void OnStaticPropertyChanged(object sender, PropertyChangedEventArgs e) {
EnsureStandardPopupAlignment();
}
}
}
...並將其附加到MainWindow:
<i:Interaction.Behaviors>
<local:WorkaroundForTheBugOfPopupBehavior />
</i:Interaction.Behaviors>
哪里:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:Test"
問題解決了。 希望這可以幫助其他人...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.