Contextmenu StaysOpen属性根本不起作用
本文关键字:不起作用 属性 StaysOpen Contextmenu | 更新日期: 2023-09-27 18:03:51
我有一个非常奇怪的问题与上下文菜单。考虑下面的简单代码:
<StackPanel>
<StackPanel.ContextMenu>
<ContextMenu x:Name="CMenu" StaysOpen="True" >
<MenuItem Header="Item 1" />
<MenuItem Header="Item 2">
<MenuItem Header="Sub item 1" />
<MenuItem Header="Sub item 2" />
<MenuItem Header="Sub item 3" />
<MenuItem Header="Sub item 4" />
</MenuItem>
<MenuItem Header="Item 3" />
<MenuItem Header="Item 4" />
</ContextMenu>
</StackPanel.ContextMenu>
<Label Content="ContextMenu Test" />
<Button Content="ClickMe" Click="Button_Click" />
</StackPanel>
我设置staysopen为true,然而,只要我点击上下文菜单之外的任何地方,它就会关闭。这个属性是用来干什么的?如何防止上下文菜单关闭?(点击clickme按钮跟踪StaysOpen状态,它总是为真)
要保持菜单打开,即使在点击后,你必须设置下面的属性为true为每个菜单项
StaysOpenOnClick="True"
所以根据您的要求,您的代码将如下所示:
<StackPanel>
<StackPanel.ContextMenu>
<ContextMenu x:Name="CMenu" StaysOpen="True" >
<MenuItem Header="Item 1" StaysOpenOnClick="True"/>
<MenuItem Header="Item 2" StaysOpenOnClick="True">
<MenuItem Header="Sub item 1" StaysOpenOnClick="True"/>
<MenuItem Header="Sub item 2" StaysOpenOnClick="True"/>
<MenuItem Header="Sub item 3" StaysOpenOnClick="True"/>
<MenuItem Header="Sub item 4" StaysOpenOnClick="True"/>
</MenuItem>
<MenuItem Header="Item 3" StaysOpenOnClick="True"/>
<MenuItem Header="Item 4" StaysOpenOnClick="True"/>
</ContextMenu>
</StackPanel.ContextMenu>
<Label Content="ContextMenu Test" />
<Button Content="ClickMe" Click="Button_Click" />
</StackPanel>
我想你应该用Popup代替:
<StackPanel>
<Popup IsOpen="True"
StaysOpen="True"
PlacementTarget="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Panel}}}">
<ListBox>
<ListBoxItem Content="1" />
<ListBoxItem Content="2" />
</ListBox>
</Popup>
<Label Content="ContextMenu Test" />
<Button Content="ClickMe" />
</StackPanel>
然而,你应该根据你的窗口的移动来注意这个弹出框的位置。意味着重新定义它的X和y