Переход от дочернего окна к родительскому окну - PullRequest
5 голосов
/ 21 декабря 2011

Я хотел бы спросить,

У меня есть окно с именем MainWindow и еще одно с именем ImportForm. В MainWindow я звоню

private void generate_Window(int num_chart) 
{ 
    Window ownedWindow = new ImportForm(num_chart); 
    ownedWindow.Owner = this;      
    ownedWindow.Show(); 
}

В дочернем окне я делаю некоторые вещи и производю переменные. как var1, var2, var3.

Я хочу, чтобы дочернее окно закрылось, чтобы вернуть var1, var2, var3 в MainWindow и вызвать одну функцию, скажем, import_chart(var1, var2, var3) ..

Любая помощь будет аппетитной. Спасибо

Ответы [ 4 ]

6 голосов
/ 21 декабря 2011

Кажется, это неуклюжий выбор дизайна. В любом случае, вот как вы можете это сделать:

MainWindow.cs:

private void generate_Window(int num_chart)
{
    Window ownedWindow = new ImportForm(num_chart, import_chart); 
    ownedWindow.Owner = this; 
    ownedWindow.Show();
}

private void import_chart(int n, string s, bool b)
{
    //Do something
}

ImportForm.cs:

private Action<int, string, bool> callback;
public ImportForm(int num_chart, Action<int, string, bool> action)
{
    InitializeComponent();
    Closed += ImportForm_Closed;
    callback = action;
}

private void ImportForm_Closed(object sender, EventArgs e)
{
    callback(0, "Test", false);
}

Просто измените Action на нужные вам типы параметров (и настройте ImportForm_Closed (...), чтобы использовать их также).

Если что-то неясно, дайте мне знать.

0 голосов
/ 21 декабря 2011

У меня есть пример из моего собственного кода.Это универсально и достаточно очевидно, что я могу поделиться этим здесь.

Я сделал что-то в этом духе.

    /// <summary>
    /// Show an InputBox similar to the pre-.NET InputBox functionality. Returns the original value when Cancel was pressed.
    /// </summary>
    /// <param name="OriginalValue">Pre-populated value in the input box</param>
    /// <param name="PromptText">Prompt text displayed on the form</param>
    /// <param name="Caption">Window caption</param>
    /// <returns>InputBoxResult structure containing both the DialogResult and the input text. Warning: The input text will always be returned regardless of the DialogResult, so don't use it if the DialogResult is Cancel.</returns>
    public static InputBoxResult Show(string OriginalValue = "", string PromptText = "", string Caption = "") {
        InputBox form = new InputBox {
           Text = Caption,
            lblPrompt = {Text = PromptText}, 
            txtInput = {Text = OriginalValue}
        };

        InputBoxResult res = new InputBoxResult();
        res.Result = form.ShowDialog();
        res.Input = form.txtInput.Text;

        return res;
    }

Я создал класс с именем InputBoxResult, например:

    /// <summary>
    /// Represents the results from an InputBox.Show call, including the DialogResult
    /// and the input data. Note that the input data is always populated with the
    /// user-entered data regardless of the DialogResult - this is inconsistent with
    /// the old InputBox behavior and may change in the future.
    /// </summary>
    public struct InputBoxResult {
        /// <summary>
        /// Describes the way the dialog was resolved (OK / Cancel)
        /// </summary>
        public DialogResult Result { get; set; }
        /// <summary>
        /// User-entered text
        /// </summary>
        public string Input { get; set; }

        /// <summary>
        /// Translate this result into a string for easy debugging
        /// </summary>
        /// <returns></returns>
        public override string ToString() {
            return "Result: " + Result.ToString() +
                "\r\nInput: " + Input.ToString();
        }
    }
0 голосов
/ 21 декабря 2011

Простой способ сделать это состоит в том, чтобы сделать var1, var2 и var3 переменные экземпляра, которые видны в области видимости родителя (например, сделать их public), а затем в MainWindow, присоединитесь к событию Closed и прочитайте переменные из (ImportForm)sender.

0 голосов
/ 21 декабря 2011

Как насчет добавления события в вашу ImportForm "ImportFinished", где вы передаете свои значения в качестве аргументов событий. Это событие вызывается в событии Close или Closing ImportForm и обрабатывается в вашем MainWindow. Вы также можете отобразить ImportForm как модальное диалоговое окно и прочитать значения, когда метод ShowDialog вернется.

...