winforms 如何在不同的子窗体中使用示例对象?

vsmadaxz  于 2022-11-16  发布在  其他
关注(0)|答案(2)|浏览(131)

我有一个“MainForm”和一个“GraphicsForm”。单击主窗体上的“新建”,将创建一个“GraphicsForm”。
问题是,当我创建多个“GraphicsForm”,而当我想保存其中一个“GraphicsForm”的内容时,我需要在“MainForm”上点击“保存”,程序会将活动的“GraphicsForm”的内容保存到一个文件中,我不知道如何将这个“GraphicsForm”的内容传递给“MainForm”进行存储。
MainForm.cs

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private ToolStripMenuItem _winMenuItem = new ToolStripMenuItem();
    private GraphicsForm _graphicsForm;
    private int _counter = 1;

    private void New_Click(objec sender, EventArgs e)
    {
        _winMenuItem.Name = "Win";
        _winMenuItem.Text = "Windows";
        int item = MainMenuStrip.Items.IndexOf(_winMenuItem);
        if (item == -1)
        {
            MainMenuStrip.Items.Add(_winMenuItem);
            MainMenuStrip.MdiWindowListItem = _winMenuItem;
        }

        _graphicsForm = new GraphicsForm();
        _graphicsForm.Name = string.Concat("Win_", _counter.ToString());
        _graphicsForm.Text = _graphicsForm.Name;
        _graphicsForm.MdiParent = this;
        _graphicsForm.Show();
        _graphicsForm.WindowState = FormWindowState.Maximized;
        _counter++;
    }

    private void Save_Click(object sender, EventArgs e)
    {
        ... // Problem here
    }

    private void Open_Click(object sender, EventArgs e)
    {
        ... // Problem here
    }
}

GraphicsForm.cs

public partial class GraphicsForm : Form
{
    //StorageDoc is a class to manage all the graphics drawn by the user in the form.

    private StorageDoc _storageDoc = new StotageDoc();

    public GraphicsForm()
    {
        InitializeComponent();
    }

    private Canvas_MouseDown()
    {
    }
    
    private Canvas_Paint()
    {
    }
    
    ...
okxuctiv

okxuctiv1#

由于MainForm是MDI窗体,因此使用ActiveMdiChild获取活动子窗体很容易。

class MainForm : Form
{
    public void OnSaveButtonClick(object sender, EventArgs e)
    {
        if(ActiveMdiChild is GraphicsForm g)
            Save(g);
    }
}
rur96b6h

rur96b6h2#

我相信这个问题以前已经得到了解答,但基本上,您将“数据存储”的示例传递给新表单。

interface ISaveForm
{
    void Save();
}

class MainForm
{
    private DataStorage _dataStorage;
    private ICollection<ISaveForm> _forms = new List<ISaveForm>();

    public void OnNew()
    {
        var subForm = new GraphicsForm(_dataStorage);
        subForm.Show();
        _forms.Add(subForm);
    }
    public void OnSave()
    {
       foreach(var form in _forms)
       {
         form.Save();
       }
    }
}
class GraphicsForm : Form,ISaveForm
{
    private DataStorage _dataStorage;

    public GraphicsForm(DataStorage dataStorage)
    {
        _dataStorage = dataStorage;
    }
    public void Save()
    {
    }
}

相关问题