winforms 如何分别保存和打开其中一个子窗体中的内容?

w80xi6nr  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(111)

有MainForm和GraphicsForm两个窗体,MainForm中有“新建”和“保存”、“打开”按钮,单击“新建”时创建一个GraphicsForm(多次单击“新建”时创建多个GraphicsForm)。
问题是,当创建了多个GraphicsForms,而用户只想将内容保存在其中一个或打开一个内容文件到其中一个,如何实现这一点?
MainForm.cs

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

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

    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(_contentDoc);
        _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)
    {
        ... // here
    }

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

GraphicsForm.cs

public partial class GraphicsForm : Form
{
    //ContentDoc is a class to manage all the graphics drawn by the user in the form.
    private ContentDoc _contentDoc = new ContentDoc();

    public GraphicsForm(ContentDoc contentDoc)
    {
        InitializeComponent();
        _contentDoc = contentDoc;
    }

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

lp0sw83n1#

父表单具有ActiveMdiChild属性,因此您可以使用来存取目前选取的GraphicsForm执行严修:

var activeGraphicsForm = ActiveMdiChild as GraphicsForm;

您还可以使用其他变体,例如模式匹配,具体取决于具体的详细信息和您的偏好。
然后,您可以将储存逻辑放在GraphicsForm的公用方法中,并从父表单呼叫它。或者,您可以将储存逻辑放在父表单中,并透过GraphicsForm中的一或多个公用属性公开要储存的数据。

相关问题