如何从用户控件中的主窗体中读取属性

Roa*_*524 5 c# user-controls winforms

我编写了一个用户控件MenuItem,它继承自Form Label.

我有一个backgroundworker线程,其IsBusy属性通过MainForm中的属性公开为IsBackgroundBusy.

如何从MenuItem用户控件中读取此属性?我目前正在使用Application.UseWaitCursor,我在backgroundworker中设置它并且它完美地工作,但是我不希望光标改变.这就是为什么我认为我可以设置的房产会好得多.

这是我的MainForm中的代码:

public partial class MainForm : Form
{
    public bool IsBackgroundBusy
    {
        get
        {
            return bwRefreshGalleries.IsBusy;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的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 );
    }
Run Code Online (Sandbox Code Playgroud)

Pet*_*iho 1

(注意:我不清楚你是否有一个实际的UserControlhere。MenuItem你显示的类继承Label,而不是UserControl。当你实际上没有处理对象时,你应该避免使用术语“用户控件”或“用户控件” UserControl) 。

如果没有完整的代码示例,很难确切地知道正确的解决方案是什么。但是,假设您以典型的方式使用BackgroundWorker,那么您只需要控件的所有者(即包含的Form)在控件更改时将必要的状态传递给控件。例如:

class MenuItem : Label
{
    public bool IsParentBusy { get; set; }
}

// I.e. 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();
}
Run Code Online (Sandbox Code Playgroud)

如果您已经有该事件的处理程序RunWorkerCompleted,则只需在此处放置用于设置属性的语句IsParentBusy,而不是添加另一个处理程序。

Application.UseWaitCursor然后,您可以只查看该属性,而不是使用该IsParentBusy属性。

您还可以使用其他机制;我确实同意一般观点,即MenuItem控件不应与您的特定Form子类绑定。如果由于某种原因上述内容在您的情况下不起作用,您需要详细说明您的问题:提供一个好的代码示例并准确解释为什么简单地让控件的容器直接管理其状态对您不起作用