我需要在加载UserControl时访问外部数据(在构造函数或加载事件中)。
它在运行模式下工作正常但在VS Designer模式下它会抛出NullReferenceException,因为在实例中静态数据没有实例化。
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
// Problem when accessing external data
Foo( AnotherClass.MyStaticData );
}
private void Foo(Data d)
{
//...
}
}
如何从控件中执行Foo( AnotherClass.MyStaticData );
行?
答案 0 :(得分:1)
在自定义控件中,您可以检查它们是否处于设计模式,并且行为方式不同。例如,您可以提供默认值而不是缺少的静态类属性,以便设计人员可以渲染您的设计时控件。
您在此页面中有很多相关信息:
Custom Design-time Control Features in Visual Studio .NET
该属性为ISite.DesigMode。
答案 1 :(得分:0)
我自己回答,这是解决方案:
使用ISite.DesignMode
显然不能在UserControl的上下文中工作,所以我在这里找到了一个可靠的解决方案:Detecting design mode from a Control's constructor
bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
答案 2 :(得分:0)
显然,不可能在Designer中访问实际的静态数据。因此,唯一的解决方案是在设计时提供虚拟对象。结合56ka和JotaBe的答案,以下是解决问题的方法:
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
if(LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{// Use a dummy value for display at design time.
Foo(desginDummyValue);
}
else
{// Use the real static data only at runtime
Foo( AnotherClass.MyStaticData );
}
}
}