单击内部控件时关闭ContextMenu

时间:2011-02-25 21:28:30

标签: wpf contextmenu

我有一个带有ContextMenu的文本框,该菜单包含一个选项卡控件。我遇到的问题是,当我单击任何选项卡控件项来更改可见选项卡控件项时,上下文菜单将关闭。有什么想法吗?

我已经尝试了ContextMenu_ContextMenuClosing事件,但它似乎没有捕获事件

<TextBox x:Name="TestCB4" TextSearch.TextPath="Name" >
    <TextBox.ContextMenu>
        <ContextMenu ContextMenuOpening="ContextMenu_ContextMenuOpening" 
                     ContextMenuClosing="ContextMenu_ContextMenuClosing"
                     MouseLeftButtonDown="ContextMenu_MouseLeftButtonDown"
                     StaysOpen="True"
                     Background="Transparent" Margin="0">
            <TabControl ContextMenuClosing="TabControl_ContextMenuClosing" Margin="0">
                <TabItem Header="User Space">
                    <WrapPanel Orientation="Horizontal"
                               HorizontalAlignment="Right"
                               Margin="10,2,2,2">
                        <Button Content="_Select" Margin="1"
                                Command="{Binding Path=SelectVendorCommand}" 
                                CommandParameter="{Binding ElementName=ucFindVendorCtrl, Path=VendorListView.SelectedItems}" />
                        <Button Content="_Add To User Space" Margin="1"
                                Command="{Binding Path=AddVendorToUserSpaceCommand}"
                                Width="120"
                                CommandParameter="{Binding ElementName=ucFindVendorCtrl, Path=VendorListView.SelectedItems}" />
                    </WrapPanel>
                </TabItem>
                <TabItem Header="Find">
                    <WrapPanel Orientation="Horizontal"
                               HorizontalAlignment="Right"
                               Margin="10,2,2,2">
                        <Button Content="_Select" Margin="1"
                                Command="{Binding Path=SelectVendorCommand}" 
                                CommandParameter="{Binding ElementName=ucFindVendorCtrl, Path=VendorListView.SelectedItems}" />
                        <Button Content="_Add To User Space" Margin="1"
                                Command="{Binding Path=AddVendorToUserSpaceCommand}"
                                Width="120"
                                CommandParameter="{Binding ElementName=ucFindVendorCtrl, Path=VendorListView.SelectedItems}" />
                    </WrapPanel>
                </TabItem>
            </TabControl>
        </ContextMenu>
    </TextBox.ContextMenu>
</TextBox>

2 个答案:

答案 0 :(得分:1)

我认为问题在于TabControl不会处理 MouseLeftButtonDown路由事件的传播,因此ContextMenu会捕获它并关闭。

如果是这种情况,那么解决方案就相当简单了。只需将TabControl包装在ContentControl中,然后在ContentControl上捕获事件MouseLeftButtonDown。在事件处理程序中执行e.Handled = true; 这样ContextMenu就无法知道用户是否点击了TabControl。

答案 1 :(得分:1)

尝试将tabcontrol放在menuItem中,例如:

<ContextMenu>
<MenuItem StaysOpenOnClick="true">
<MenuItem.Header>
...your TabControl
</MenuItem.Header>
</MenuItem>
</ContextMenu>

我希望它有所帮助。