簡體   English   中英

C#在沒有新實例的情況下在表單之間傳遞特定值

[英]C# Specific value passing between forms without new instance

我有一個C#應用程序,允許用戶記錄游戲中發生的某些事件。 為了簡單起見,我將它們ParentFormChildForm

99%的時間使用ParentForm記錄常見事件。 如用戶點擊這被表示PictureBoxTag將財產PictureBox被添加到ListBox 當發生“罕見”事件時,用戶可以單擊ParentForm上的“日志罕見事件”按鈕以打開ChildForm ,該子ChildForm將打開一組“罕見事件” PictureBoxes ,其功能與ParentForm中的ParentForm 面臨的挑戰是,我希望將這些常見事件和罕見事件記錄到同一個ListBox ,因此我試圖找出如何將ChildForm上的PictureBox單擊(以及此PictureBox后續TagChildFormChildForm上的ListBox 。 。

ParentForm打開時ChildForm 不會關閉,需要保持打開狀態。

ParentForm代碼中,我已經有了捕獲PictureBox單擊並抓住Tag所需的Tag ,以及處理將其添加到ListBox ,因此,如果我可以使用它們,那就太好了。

到目前為止,這是我為家長所做的嘗試:

// This file is EventLogger.cs
using rareEvent;
namespace mainWindow {
    public partial class EventLogger : Form {
        // In the ParentForm (listeners for PictureBox clicks are handled elsewhere)
        public void pictureBox_Click(object sender, EventArgs e) {

            PictureBox pbSender = (PictureBox) sender;

            // Open new window and handle "rare" drops
            if (pbSender.Tag.ToString() == "rare") {

                // Open rare form
                EventLogger.RareForm rare = new EventLogger.RareForm();
                rare.Show();
            }
        }
    }
}

這是孩子:

// This file is Rare.cs
using EventLogger;
namespace rareEvent {
    public partial class rareEventForm : Form {

        // In the ChildForm
        private void pictureBox_Click(object sender, EventArgs e) {

            // Does not compile if form is not instantiated, but I do not
            // want a new instance
            EventLogger form;
            form.pictureBox_Click(sender, e);
        }
    }
}

我想像這樣的東西會工作,但它給了錯誤

The type or namespace name 'EventLogger' does not exist in the namespace
'mainWindow' (are you missing an assembly reference?)

任何幫助將非常感激。 我發現的所有其他有關表單之間傳遞價值的示例似乎都在創建新的實例,這些實例我不希望使用,或者已經使用了8年並且無法使用。

贊賞!

編輯:代碼已更新為在每個文件中using <namespace> 問題依然存在不能夠發送兩種形式之間的值,而無需使用new (請參閱將注釋答案)

在第一種形式中,像我的form1一樣在此處創建一個實例。 它必須是靜態的,並且要訪問的所有數據類型都應該是公共的。

//FORM1
public partial class Form1 : Form
{
    //Instance of this form
    public static Form1 instance;

    //For testing
    public string myProperty = "TEST";

    //Assign instance to this either in the constructor on on load like this 
    public Form1()
    {

        InitializeComponent();
        instance = this;
    }
    //or
    private void Form1_Load(object sender, EventArgs e)
    {
        //Assign the instance to this class
        instance = this;
    }

然后在form2中,當調用EventLogger.RareForm時,很少= new EventLogger.RareForm();。 代替新形式

EventLogger.RareForm rare = EventLogger.RareForm.instance

或者就我而言

Form1 frm = Form1.instance;

然后,我像這樣從Form2檢查表格1的屬性

Console.WriteLine(frm.myProperty);

輸出為“測試”

麻煩大喊大叫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM