How do I feed values to the statusStrip from a form control?

让人想犯罪 __ 提交于 2019-11-29 16:26:02

You have multiple options to update status:

  1. Inject an Action<Point> in the user control
  2. Create a StatusUpdate event in the user control
  3. You also can access the control using hierarchy of controls, for example in the user control this.ParentForm is your parent form and you can find the target control using Controls collection or by making it public in the form.

The first two options are much better because decouple your control from the form and your user control can be used on many forms and other containers this way. Providing a way of updating status is up to container.

The best option is creating and consuming the event.

1- Inject an Action<Point> in the user control

Inject an Action<Point> in the user control and use it in MouseMove. To do so, put this in User Control:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Action<Point> StatusUpdate{ get; set; }

//Don't forget to assign the method to MouseMove event in your user control 
private void UserControl1_MouseMove(object sender, MouseEventArgs e)
{
    if (StatusUpdate!= null)
        StatusUpdate(e.Location);
}

And put this code on Form:

private void Form1_Load(object sender, EventArgs e)
{
    this.userControl11.StatusUpdate= p => this.toolStripStatusLabel1.Text=p.ToString();
}

2- Create a StatusUpdate event in the user control

Create a StatusUpdate event in the user control and raise it in MouseMove and consume the event in the form. Also you can use the MouseMove event itself.

To do so, put this code in user control:

public event EventHandler<MouseEventArgs> StatusUpdate;
public void OnStatusUpdate(MouseEventArgs e)
{
    var handler = StatusUpdate;
    if (handler != null)
        handler(this, e);
}

//Don't forget to assign the method to MouseMove event in your user control 
private void UserControl1_MouseMove(object sender, MouseEventArgs e)
{
    OnStatusUpdate(e);
}

And then put in form, put this code:

//Don't forget to assign the method to StatusUpdate event in form  
void userControl11_StatusUpdate(object sender, MouseEventArgs e)
{
    this.toolStripStatusLabel1.Text = e.Location.ToString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!