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

本文关键字:窗体 读取 属性 用户 控件 | 更新日期: 2023-09-27 18:36:43

我编写了一个用户控件 MenuItem,它继承自表单标签。

我有一个后台工作线程,其 IsBusy 属性通过 MainForm 中的属性作为 IsBackgroundBusy。

如何从菜单项用户控件读取此属性?我目前正在使用Application.UseWaitCursor,我在后台工作者中设置了它,它工作得很好,但是我不希望光标改变。这就是为什么我认为我可以设置的属性会好得多。

这是我的主窗体中的代码:

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

这是我的用户控件的代码:

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 );
    }

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

(注意:我不清楚你在这里是否有实际的UserControl。您显示的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();
}

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

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

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