How to read a property from my main form in a user control

I wrote a MenuItem user control that inherits from the form label.

I have a backgroundworker thread whose IsBusy property opens through the MainForm property as IsBackgroundBusy.

How did I read this property from MenuItem user control? I am currently using Application.UseWaitCursor and I set it to backgroundworker and it works fine, however I do not want the cursor to change. That's why I decided that a property that I could set would be much better.

Here is the code in my MainForm:

public partial class MainForm : Form { public bool IsBackgroundBusy { get { return bwRefreshGalleries.IsBusy; } } 

Here is the code for my usercontrol:

 public partial class MenuItem: Label { private bool _disableIfBusy = false; [Description("Change color if Application.UseWaitCursor is True")] public bool DisableIfBusy { get { return _disableIfBusy; } set { _disableIfBusy = value; } } public MenuItem() { InitializeComponent(); } protected override void OnMouseEnter( EventArgs e ) { if ( Application.UseWaitCursor && _disableIfBusy ) { this.BackColor = SystemColors.ControlDark; } else { this.BackColor = SystemColors.Control; } base.OnMouseEnter( e ); } 
+5
source share
1 answer

(Note: it’s not clear to me if you have the actual UserControl here or not. The MenuItem class that you show inherits the Label , not the UserControl . You should probably avoid using the term usercontrol, or β€œuser control,” unless you actually dealing with a UserControl object).

Lack of a complete code example, it is difficult to know exactly what the correct solution is. However, assuming that you are using BackgroundWorker in typical mode, you just need the owner of the control (i.e. Containing Form ) to pass the necessary state to the control as it changes. For instance:.

 class MenuItem : Label { public bool IsParentBusy { get; set; } } // Ie some method where you are handling the BackgroundWorker void button1_Click(object sender, EventArgs e) { // ...some other initialization... bwRefreshGalleries.RunWorkerCompleted += (sender1, e1) => { menuItem1.IsParentBusy = false; }; menuItem1.ParentIsBusy = true; bwRefreshGalleries.RunAsync(); } 

If you already have a RunWorkerCompleted event RunWorkerCompleted , simply set the statement to set the IsParentBusy property instead of adding another handler.

Then, instead of using the Application.UseWaitCursor property, you can just look at the IsParentBusy property.

There are other mechanisms that you could use; I agree with the general statement that the MenuItem control should not bind to your specific subclass of Form . If for some reason the above does not work in your case, you need to dwell on your question: provide a good code example and explain why just having a control container controls its state directly, does not work for you

+1
source

Source: https://habr.com/ru/post/1210597/


All Articles