[英]How do I read a property from my main form in a user control
我编写了一个用户控件MenuItem,它继承自Form Label。
我有一个backgroundworker线程,其IsBusy属性通过MainForm中的属性公开为IsBackgroundBusy。
如何从MenuItem用户控件中读取此属性? 我目前正在使用Application.UseWaitCursor,我在backgroundworker中设置它并且它完美地工作,但是我不希望光标改变。 这就是为什么我认为我可以设置的房产会好得多。
这是我的MainForm中的代码:
public partial class MainForm : Form
{
public bool IsBackgroundBusy
{
get
{
return bwRefreshGalleries.IsBusy;
}
}
这是我的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 );
}
(注意:我不清楚你是否在这里有一个实际的UserControl
。你显示的MenuItem
类继承Label
而不是UserControl
。当你没有实际交易时,你应该避免使用术语“usercontrol”或“user control”使用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
子类。 如果由于某种原因上述情况不适用于您的情况,您需要详细说明您的问题:提供一个好的代码示例并解释为什么简单地让控件的容器直接管理其状态对您不起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.