使用UserControl上的按钮隐藏父窗体上的按钮 [英] Hide Button on parent form using a button on UserControl

查看:64
本文介绍了使用UserControl上的按钮隐藏父窗体上的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我有一个Windows窗体,其中有一个UserControl和两个按钮。

在用户控件上我有一个按钮。当我点击UserControl上的Button时,我想在窗体上禁用这两个按钮。



谢谢

Hello,

I have a Windows form which has a UserControl and two buttons.
On user Control i have a button.I want to disable those two buttons on form when i click on Button on UserControl.

Thanks

推荐答案

public partial class xyz_Usercontrol : UserControl
{

    public xyz_Usercontrol()
    {
        InitializeComponent();


    }
    public Button mybt
    {
   //button1 is the button on your user control
        get { return this.button1; }

    }

}

   //code inside your parent form

        private void Form1_Load(object sender, EventArgs e)
        {

            Button tt = xyz_Usercontrol1.mybt;
            tt.Click += tt_Click;
        }

        void tt_Click(object sender, EventArgs e)
        {
        //button1 is the button on your parent form
            button1.Visible = false;
        }


这听起来不是一个好的设计理念,但有些情况需要做类似的事情。问题是:用户控件不应该知道使用它的表单。



但问题很简单:你可以使用父表单传递给控件的一些委托方法,这样控件就可以调用它。更好的是,它应该使用一些甚至是用户控件进行封装。这就是:例如:

It does not sound like a good design idea, but there are real cases when you need to do something similar. The problem is: the user control is not supposed to "know" anything about the form using it.

But the problem is simple: you could use some delegate method passed by the parent form to the control, so the control could call it. Better yet, it should be encapsulated using some even of the user control. This is how, for example:
public class MyUserControl : UserControl {

    public MyUserControl() {
        //...
        myButton.Click += () => {
            if (MyButtonClicked != null)
                MyButtonClicked.Invoke(myButton, new System.EventArgs);
        }
    }

    public event System.EventHandler MyButtonClicked;

    Button myButton;

}

使用此控件的父窗体可以初始化它并将一些事件处理程序添加到您的调用列表 MyUserControl.MyButtonClicked 事件实例。这样, MyButtonClicked 的实例将调用此事件,而不是知道委托在调用列表中放置的内容。它们属于父控件。这样,两个控件(父窗体和用户控件)的行为细节被正确封装,控件的内部被隔离。



顺便说一句,这是控制反转概念的一个简单示例: http://en.wikipedia.org/wiki/Inversion_of_control [ ^ ]。



-SA

The parent form using this control can initialize it and add some event handler to the invocation list of you MyUserControl.MyButtonClicked event instance. This way, the instance of MyButtonClicked will invoke this event not "knowing" what the delegates put in the invocation list really do; they belong to the parent control. This way, the behavior detail of the two control (parent form and your user control) are properly encapsulated and controls' internals are isolated.

By the way, this is a simple example pf the inversion of control concept: http://en.wikipedia.org/wiki/Inversion_of_control[^].

—SA


这篇关于使用UserControl上的按钮隐藏父窗体上的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆