在我的項目中我有一個用戶控件;當按下這個用戶控件上的一個按鈕時,我希望它改變一個存儲在主Winform中的變量,而不是用戶控件。如何在C#中的用戶控件中控制winform的其他部分?
這怎麼辦?
我已經試過這
namespace.class.variable =
,但它說,它不能被訪問,由於它的保護。
在我的項目中我有一個用戶控件;當按下這個用戶控件上的一個按鈕時,我希望它改變一個存儲在主Winform中的變量,而不是用戶控件。如何在C#中的用戶控件中控制winform的其他部分?
這怎麼辦?
我已經試過這
namespace.class.variable =
,但它說,它不能被訪問,由於它的保護。
用戶控件應該是一個孤立的整體,一個容器。 您需要使用事件。
想一想如何讓普通的Button控件在常規的TextBox控件中填充一些文本?
TextBox不知道按鈕和按鈕不知道您的文本框。他們是單獨的控制。 您所做的是訂閱按鈕的單擊事件,然後告訴文本框控件更改其文本。
與此類似,您的用戶控件需要提供以及事件,只要點擊按鈕或其他操作發生,您就可以觸發事件。
那就是全部控件應該做的,提供一個事件並觸發它。
然後,您可以從容納用戶控件的表單中訂閱該事件,並在該事件處理程序中根據需要更改其他控件的屬性。
以下是如何和事件工作的簡要示例。查找更多信息here
這應該是你的用戶控件
//A delegate that describe's your event's signature
public delegate void ChangedEventHandler(object sender, EventArgs e);
//The actual Event declaration
public event ChangedEventHandler Changed;
//When appropriate, trigger the event from the user control
if (Changed != null) {
Changed(this, e);
}
對不起,但我仍然感到困惑。如果我在'userControl1'上有'button1',如果'label1'不在用戶控件中,但是在'userControl1'所在的winform中,如何讓'button1'中的文本變爲'hello'? –
你不應該直接做。這就是我告訴你的。用戶控件**內的任何內容都不能**訪問用戶控件之外的其他控件。這不是用戶控件的用途。 您可以聲明button1在您的用戶控件中公開,然後從表單訂閱button1的單擊事件,然後從那裏設置label1上的文本。 – irreal
小介紹裏面,你需要做什麼。 這是一個小MVP程序,當你點擊按鈕時它會顯示消息。
//Your MainForm class
public class MainForm: Form,IMainView
{
public event Action ButtonClicked;
public MainForm()
{
InitializeComponent();
button.Click += (sender, args) =>
{
var handler = ButtonClicked;
if (handler != null) handler(sender, args);
};
}
public void ShowError(string message)
{
MessageBox.Show(message);
}
}
//Your MainForm interface. What lies here will become accessible in Presenter
public interface IMainView : IView
{
event Action ButtonClicked;
}
//View interface
public interface IView
{
void ShowError(string message);
}
//Your MainForm Presenter class which will do all work behind GUI
public class MainPresenter : BasePresenter<IMainView>
{
public MainPresenter(IMainView view)
: base(view)
{
view.ButtonClicked += view_ButtonClicked;
}
void view_ButtonClicked()
{
View.ShowError("Clicked!");
}
}
//Base class for all presenters
public abstract class BasePresenter<TView> : IPresenter
where TView : IView
{
protected TView View { get; private set; }
protected BasePresenter(TView view)
{
View = view;
}
}
//Presenter interface
public interface IPresenter
{
}
相當複雜的方式來做一個簡單的事件處理程序... –
最好的辦法是使用事件 –
如果變量是靜態的,那麼你可能需要公開它。 – Adil
你能跟我說說嗎? @SamiKuhmonen –