如何使用主类更改子类中的所选元素?

时间:2019-03-02 08:39:33

标签: c# winforms

我的代码有问题。我想清除子类中的直方图并设置新参数。但是当我在主类FormResult formChild = new FormResult();和下一个formChild.histogram.Series.Clear();中使用时,没有任何效果,也看不到任何结果。

在主班:

private void stretchHistogram_Click(object sender, EventArgs e)
{
    FormResult formChild = new FormResult();
    formChild.histogram.Series.Clear();
    formChild.histogram.Show();        
}

子类:

public partial class FormResult : Form
{
    private const int MIN_VALUE = 0;
    private const int MAX_VALUE = 255;
    private int[] valueHistogram = new int[MAX_VALUE + 1];

    public FormResult()
    {
        InitializeComponent();
    }

    private void FormResult_Load(object sender, EventArgs e)
    {
        var mainForm = new APOForm();

        FormResult formResult = new FormResult();
        formResult.Owner = this;

        // Generate PictureBox
        pictureBox.Image = Image.FromFile(mainForm.getMyPath());
        pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
        pictureBox.Show();

        // Change image for bitmap array
        Bitmap bm = (Bitmap)pictureBox.Image;

        // Create table for pixel value for histogram

        for(int i=0; i<MAX_VALUE; ++i)
        {
            valueHistogram[i] = 0;
        }

        for (int x=0; x<bm.Width; ++x)
        {
            for(int y=0; y<bm.Height; ++y)
            {
                Color c = bm.GetPixel(x, y);
                valueHistogram[c.R] += 1;
            }
        }

        // ------------ Generate histogram
        histogram.ChartAreas[0].AxisX.Minimum = MIN_VALUE;
        histogram.ChartAreas[0].AxisX.Maximum = MAX_VALUE;
        histogram.ChartAreas[0].AxisY.Minimum = 0;
        histogram.Series.Clear();
        histogram.Series.Add("S");
        histogram.Series["S"].IsVisibleInLegend = false;

        int maxAxisY = 0;

        for (int i=0; i< MAX_VALUE+1; ++i)
        {
            if(maxAxisY < valueHistogram[i]) { maxAxisY = valueHistogram[i];  }

            histogram.Series["S"].Points.AddXY(i, valueHistogram[i]);  
        }

        histogram.ChartAreas[0].AxisY.Maximum = maxAxisY;
        histogram.Show();
    }
}

1 个答案:

答案 0 :(得分:0)

您应该在主表单中保留对子表单的引用,并使用该引用来控制创建的子表单。

public class APOForm : Form
{
    FormResult formChild;

    // this is a pseudo method to show how to create a sub form.
    private void ShowChildForm()
    {
         formChild = new FormResult();
         formChild.MdiParent = this;
         formChild.Show();
    }

    private void stretchHistogram_Click(object sender, EventArgs e)
    {
        if(formChild != null)
        {
            formChild.histogram.Series.Clear();
            formChild.histogram.Show();
        }    
    }
}

FormResult类中,不需要任何新形式。

public partial class FormResult : Form
{
    private void FormResult_Load(object sender, EventArgs e)
    {
        //var mainForm = new APOForm();

        //FormResult formResult = new FormResult();
        //formResult.Owner = this;

        ......
    }
}