单击后保持打开上下文菜单

时间:2014-09-03 10:16:32

标签: c# wpf contextmenu

我已经通过上下文菜单获得了数据网格。它以编程方式初始化:

contextMenu = new ContextMenu();

foreach (var col in this.Columns)
{
    var checkBox = new MenuItem()
    {
        Header = col.Header
    };
    Binding myBinding = new Binding("Visibility");
    myBinding.Mode = BindingMode.TwoWay;
    myBinding.Converter = new IsCheckedToVisibilityConverter();
    checkBox.DataContext = col;
    checkBox.SetBinding(MenuItem.IsCheckedProperty, myBinding);
    checkBox.Click += checkBox_Click;
    checkBox.Checked += checkBox_Checked;
    checkBox.Unchecked += checkBox_Unchecked;
    contextMenu.Items.Add(checkBox);

}

它工作得很好,但我想在检查\取消选中菜单项后保持打开上下文菜单。有什么想法吗?

2 个答案:

答案 0 :(得分:6)

添加checkBox.StaysOpenOnClick = true;按预期工作

contextMenu = new ContextMenu();

            foreach (var col in this.Columns)
            {
                var checkBox = new MenuItem()
                {
                    Header = col.Header
                };
                //binding
                Binding myBinding = new Binding("Visibility");
                myBinding.Mode = BindingMode.TwoWay;
                myBinding.Converter = new IsCheckedToVisibilityConverter();
                checkBox.DataContext = col;
                checkBox.SetBinding(MenuItem.IsCheckedProperty, myBinding);
                checkBox.Click += checkBox_Click;
                checkBox.Checked += checkBox_Checked;
                checkBox.Unchecked += checkBox_Unchecked;
                checkBox.StaysOpenOnClick = true;
                contextMenu.Items.Add(checkBox);

            }

答案 1 :(得分:0)

您可以尝试:

private bool close= true; 

private void CheckBox1_CheckedChanged(Object sender, EventArgs e)
{
 close= false; 
}

private void contextMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
  e.Cancel = !close;
  CloseContextMenu = true;
}