Windows 窗体之创建动态上下文菜单.net -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    以下演练显示如何更改每个控件的菜单项 创建应用程序 以下步骤将创建一个 Windows 应用程序,它具有包含两个控件的窗体,

Windows 窗体之创建动态上下文菜单.net

。在运行时,如果右击每个控件(只要它具有焦点,即被选定),将显示相应的上下文菜单。RadioButton 控件的上下文菜单将包含两个项;Chec

    以下演练显示如何更改每个控件的菜单项

    创建应用程序

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

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

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

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

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

    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 创建一个事件处理程序,

电脑资料

Windows 窗体之创建动态上下文菜单.net》(https://www.unjs.com)。添加如下代码,检验窗体的 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;

    }

    原文转自:http://www.ltesting.net

最新文章