绑定到ContextMenu.IsOpen时的WPF上次菜单在第一次调用时在屏幕的左上角闪烁

时间:2017-05-21 15:46:24

标签: c# wpf contextmenu

我已经解决了这个问题,但在我看来,这个解决方案是反直觉的,所以我为其他遇到这个问题的人发了这个帖子。

下面是一个View模型,其属性ShouldShow将绑定到视图中的上下文菜单:

public class VMMain : INotifyPropertyChanged
{
    private bool shouldShow;

    public event PropertyChangedEventHandler PropertyChanged;

    public bool ShouldShow
    {
        get { return shouldShow; }
        set
        {
            shouldShow = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShouldShow)));
        }
    }
}

这是xaml:

<Window x:Class="TestContextMenuBug.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestContextMenuBug"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

    <Grid Background="Transparent">
        <Grid.ContextMenu>
            <ContextMenu IsOpen="{Binding ShouldShow}">
                <MenuItem Header="Menu Item" />
            </ContextMenu>
        </Grid.ContextMenu>
    </Grid>
</Window>

第一次在此窗口中右键单击时,上下文菜单将在屏幕的左上角短暂闪烁。所有后续点击都能正常运行。

1 个答案:

答案 0 :(得分:0)

谢天谢地,这个问题的解决方案很容易。

private bool shouldShow = true;

将支持变量初始化为true可以解决此问题。我的解决方案是反直觉的,我的上下文菜单最初没有打开,所以为什么要将绑定到IsOpen的属性初始化为true