[英]C# How to access setter method on main form, from my user control?
我有一個UserControl,其中包含一個面板,該面板包含一個圖片框。 當我將鼠標移到圖片框上時,我想更新MainForm上的標簽。 我在主窗體上有一個get / set方法,但是如何使用它呢? 謝謝
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
public String MouseCords
{
get { return this.MouseCordsDisplayLabel.Text; }
set { this.MouseCordsDisplayLabel.Text = value; }
}
}
public partial class ScoreUserControl : UserControl
{
public ScoreUserControl()
{
InitializeComponent();
}
private void ScorePictureBox_MouseMove(object sender, MouseEventArgs e)
{
// MainForm.MouseCords("Hello"); //What goes here?
}
}
實際上,您可以按照以下方式進行操作:
((MainForm)this.ParentForm).MouseCords = "Some Value Here";
但是正確的方法是處理像Felice Pollano這樣的事件:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
this.myCustomControlInstanse.PicureBoxMouseMove += new EventHandler<StringEventArgs>(myCustomControlInstanse_PicureBoxMouseMove);
}
private void myCustomControlInstanse_PicureBoxMouseMove(object sender, StringEventArgs e)
{
this.MouseCordsDisplayLabel = e.Value // here is your value
}
}
public class StringEventArgs : EventArgs
{
public string Value { get; set; }
}
public partial class ScoreUserControl : UserControl
{
public event EventHandler<StringEventArgs> PicureBoxMouseMove;
public void OnPicureBoxMouseMove(String value)
{
if (this.PicureBoxMouseMove != null)
this.PicureBoxMouseMove(this, new StringEventArgs { Value = value });
}
public ScoreUserControl()
{
InitializeComponent();
}
private void ScorePictureBox_MouseMove(object sender, MouseEventArgs e)
{
this.OnPicureBoxMouseMove("Some Text Here");
}
}
理想情況下,您應該為此發起一個事件。
建立代表
public delegate void Update();
在用戶控件中
public class MyUserControl : UserControl
{
public event Update OnUpdate;
}
在主窗體上注冊一個用於用戶控件事件的處理程序。
public class Main
{
public Main()
{
myUserControl.OnUpdate += new Update(this.UpdateHandler);
}
void UpdateHandler()
{
//you can set the delegate with sm arguments
//set a property here
}
}
在用戶控制下,
要在按鈕上引發事件,請單擊
做這個
OnUpdate();
這可能會給您一個想法...
public partial class ScoreUserControl : UserControl
{
public ScoreUserControl()
{
InitializeComponent();
}
private void ScorePictureBox_MouseMove(object sender, MouseEventArgs e)
{
// MainForm.MouseCords("Hello"); //What goes here?
MainForm parent = this.ParentForm as MainForm;
if (parent != null) parent.MouseCordsDisplayLabel.Text = "Hello";
}
}
您有幾種選擇:
this.ParentForm
轉換為MainForm類,然后您便有了引用。 選項2和3較為舒適和懶惰,但是代價是用戶控件必須了解特定的類MainForm。 第一個選項的優點是您可以在另一個項目中重用用戶控件,因為它不了解MainForm類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.