为什么标签2.Form1 中的文本不会从新类更新

本文关键字:新类 更新 文本 标签 Form1 为什么 | 更新日期: 2023-09-27 18:37:08

在 Form1 中,我在设计器中有 label2,并添加了一个代码:

public void lbl2(string text)
        {
            label2.Text = text;
        }

在新类顶部,我添加了:

private static AnimationEditor.Form1 fr1 = new AnimationEditor.Form1();

并在新的类事件中更新标签2。像这样的文字:

int ISampleGrabberCB.BufferCB(double sampleTime, IntPtr pBuffer, int bufferLen)
        {
            using (var bitmap = new Bitmap(_width, _height, _width * 3, PixelFormat.Format24bppRgb, pBuffer))
            {
                bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
                if (SaveToDisc)
                {
                    String tempFile = _outFolder + _frameId + ".bmp";
                    if (File.Exists(tempFile))
                    {
                        fr1.lbl2(_frameId.ToString();
                    }
                    else
                    {
                        bitmap.Save(Path.Combine(_outFolder, _frameId + ".bmp"));
                    }
                    _frameId++;
                }
                else
                {
                    if (Images == null)
                        Images = new List<Bitmap>();
                    Images.Add((Bitmap)bitmap.Clone());
                }
            }
            return 0;
        }

正在进行更新的是:

fr1.lbl2(_frameId.ToString();

现在,我在新类的这一行中使用了断点,并在标签 2 的 Form1 中使用了断点。公共函数中的文本,我看到 label2 文本首先更改其 0,然后更改 1,然后更改 2,依此类推。

但实际上,当 im 运行应用程序时,label2 会实时更改其文本 saty 作为标签 2

这是我单击它时 Form1 按钮单击事件,它正在执行新的类代码:

private void button5_Click(object sender, EventArgs e)
        {
            wmv = new Polkan.DataSource.WmvAdapter(@"d:'VIDEO0040.3gp", sf);
            wmv.SaveToDisc = true;
            wmv.Start();
            wmv.WaitUntilDone();
        }

为什么标签2.Form1 中的文本不会从新类更新

我认为快速的答案是将标签的引用传递给类:

private Label lbl;
public WmvAdapter(string file, string outFolder, Label label) {
  // yada-yada-yada
  lbl = label;
}

您的例程将更改为:

if (File.Exists(tempFile))
{
  lbl.Text = _frameId.ToString();
}

您的点击事件:

private void button5_Click(object sender, EventArgs e)
{
  wmv = new Polkan.DataSource.WmvAdapter(@"d:'VIDEO0040.3gp", sf, this.Label2);
  wmv.SaveToDisc = true;
  wmv.Start();
  wmv.WaitUntilDone();
}

更长的答案是让你的班级提出一个事件并让你的表格倾听它。

让你的班级了解表单并不是最好的编码实践。