Contextmenu StaysOpen属性根本不起作用

时间:2016-08-24 15:16:51

标签: c# wpf

我对contextmenu有一个非常奇怪的问题。考虑一下这个简单的代码:

<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状态,它始终为真)

2 个答案:

答案 0 :(得分:2)

要在单击后保持菜单打开,您必须为每个menuitem

将以下属性设置为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>

答案 1 :(得分:0)

我想你需要使用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.