WPF 当绑定到 ContextMenu.IsOpen 上下文菜单在第一次调用时在屏幕左上角闪烁
WPF When Binding to ContextMenu.IsOpen Context Menu flashes in top left corner of screen on first invocation
我已经解决了这个问题,但在我看来这个解决方案是违反直觉的,所以我正在为 运行 的其他人做这个 post。
下面是一个带有 属性 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>
当您第一次在此 window 中右键单击时,上下文菜单将在屏幕左上角短暂闪烁。所有后续点击均正常工作。
谢天谢地,解决这个问题很简单。
private bool shouldShow = true;
将支持变量初始化为 true
可以解决此问题。虽然对我来说解决方案是违反直觉的,但我的上下文菜单最初没有打开,所以为什么将绑定到 IsOpen
的 属性 初始化为 true
?
我已经解决了这个问题,但在我看来这个解决方案是违反直觉的,所以我正在为 运行 的其他人做这个 post。
下面是一个带有 属性 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>
当您第一次在此 window 中右键单击时,上下文菜单将在屏幕左上角短暂闪烁。所有后续点击均正常工作。
谢天谢地,解决这个问题很简单。
private bool shouldShow = true;
将支持变量初始化为 true
可以解决此问题。虽然对我来说解决方案是违反直觉的,但我的上下文菜单最初没有打开,所以为什么将绑定到 IsOpen
的 属性 初始化为 true
?