首页 > 编程 > C# > 正文

在窗体中创建动态上下文菜单

2023-05-10 18:49:23
字体:
来源:转载
供稿:网友

若要节省创建应用程序所需的时间并减少代码量,可以让多个控件共享单个上下文菜单对象。利用一个只包含该控件必需菜单项的“动态”上下文菜单(或快捷方式菜单),可以减少应用程序中控件所需的上下文菜单总数。以下演练显示如何更改每个控件的菜单项。

创建应用程序

以下步骤将创建一个 Windows 应用程序,它具有包含两个控件的窗体。在运行时,如果右击每个控件(只要它具有焦点,即被选定),将显示相应的上下文菜单。RadioButton 控件的上下文菜单将包含两个项;CheckBox 控件的上下文菜单将包含三个项。

在 Windows 窗体上创建动态上下文菜单

1.创建新的Windows 应用程序。

2.将一个“复选框”(CheckBox) 控件和一个“RadioButton”控件从“工具箱”拖到窗体上。

虽然任何两个(或更多个)控件都可以共享一个上下文菜单,但使具有类似ming令的控件共享上下文菜单也是有好处的,因为这样可以减少必需动态显示及隐藏的量。

3.双击“工具箱”中的“ContextMenu”组件,将其添加到窗体中。它将成为共享的上下文菜单。

4.在“属性”窗口中,将 CheckBox 控件和 RadioButton 控件的 ContextMenu 属性设置为 ContextMenu1(在 C# 中为 contextMenu1)。

5.在“属性”窗口中,将 CheckBox 控件的 ThreeState 属性设置为 true。

6.从设计器中双击 ContextMenu 组件,为该组件的 Popup 事件创建默认的处理程序。在事件处理程序中插入执行以下任务的代码:

·添加两个菜单项,一个表示控件的 Checked 状态,另一个表示 Unchecked 状态。

·用 If 语句检验 CheckBox 控件是否为窗体上的 SourceControl。根据检验结果,动态地添加第三个菜单项,该菜单项表示控件的 Indeterminate 状态。

以下示例显示如何使用 Add 方法来设置菜单项的 Text 属性以及如何定义与该菜单项相关联的事件处理程序。

private void contextMenu1_Popup(object sender, System.EventArgs e)
        {
                contextMenu1.MenuItems.Clear();
                contextMenu1.MenuItems.Add("Checked",new System.EventHandler(this.Checked_OnClick));
                contextMenu1.MenuItems.Add("Unchecked",new System.EventHandler(this.Unchecked_OnClick));
                if (contextMenu1.SourceControl == checkBox1)
                {
                        this.contextMenu1.MenuItems.Add("Indeterminate", new System.EventHandler(this.Indeterminate_OnClick));
                }
        }

为 MenuItem1 创建一个事件处理程序。添加如下代码,检验窗体的 SourceControl 属性,然后根据检验结果设置 RadioButton 或 CheckBox 控件的 Checked 属性:

protected void Checked_OnClick(System.Object sender, System.EventArgs e)
       {
               if (contextMenu1.SourceControl == radioButton1)
                       radioButton1.Checked = true;
               else if (contextMenu1.SourceControl == checkBox1)
                       checkBox1.Checked = true;
        }

注意:此示例在 Indeterminate_OnClick 事件处理程序中使用 CheckState 属性将 CheckBox 控件设置为 Indeterminate。

为 MenuItem2 创建类似的事件处理程序。为该事件处理程序输入如下代码:

protected void Unchecked_OnClick(System.Object sender, System.EventArgs e)
        {
                if (contextMenu1.SourceControl == radioButton1)
                        radioButton1.Checked = false;
                else if (contextMenu1.SourceControl == checkBox1)
                        checkBox1.Checked = false;
        }

为 MenuItem3 创建类似的事件处理程序。为该事件处理程序输入如下代码,确保将事件命名为 Indeterminate_OnClick:

protected void Indeterminate_OnClick(System.Object sender, System.EventArgs e)
        {
                if(contextMenu1.SourceControl == checkBox1)
                        checkBox1.CheckState = System.Windows.Forms.CheckState.Indeterminate;
        }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表