控件是对象的观察者,我无法注册,因为尚未创建 window 句柄

A Control is an observer of an object and I it fails to register because window handle has not been created

我有一个 windows 表单控件 MyControl,它是一个对象的观察者。该对象有一些图像。控件有 System.Windows.Forms.ProgressBar progressBar。在注册对象时通知图像的控件并且控件递增进度条的值,这会抛出“在创建 window 句柄之前无法在控件上调用 Invoke 或 BeginInvoke”。此控件位于 window 内的另一个控件内,所有这些都发生在构造函数链中。

我的理解是 创建 window 之后应该进行注册,但我认为我无法使用当前架构来完成。以前只是在构造函数中询问图片计数的对象,但是图片是异步添加的,所以我不想再依赖计数器了。

interface IImagesObserver
{
  void onImageAdded();
}
class MyControl : IImagesObserver
{
  public MyControl(MyObject object)
  {
    InitializeComponent();
    ...
    object.register(this);
  }

  void IObjectOnserver.onImageAdded()
  {
    Invoke((MethodInvoker)delegate
    {
      progressBar.Value++;
      Invalidate();
    });
  }
}
class MyObject
{
  public void register(IImagesObserver observer)
  {
    foreach( var img in images)
      observer.onImageAdded();
  }
}

您可以覆盖 OnHandleCreated and call the register method from there. Or you can force the creation of the control handle in the constructor with CreateControl。 您还应该在观察者被处置之前注销它。 Control.Dispose 方法的覆盖将是一个很好的地方(在调用 base.Dispose 之前)。