簡體   English   中英

窗口關閉后返回值WPF-MVVM

[英]return value after window closes WPF-MVVM

我有一個僅包含一個文本框和保存按鈕的用戶控件。 我將此用戶控件顯示為“對話框”窗口。 用戶在文本框中輸入評論並單擊“保存”按鈕后,我將關閉對話框窗口。

我成功做到了。 我的問題是我想將文本框值傳遞到主窗口。 我該如何通過? 這是我的代碼

//顯示窗口

 var window = new RadWindow
           {
              Owner = Application.Current.MainWindow,
              WindowStartupLocation = WindowStartupLocation.CenterOwner
           };          
        window.Content = control;
        window.SizeToContent = true;
        window.Header = header;  
        window.ShowDialog()

使用ICommand在ViewModel中關閉窗口

private void SaveCommentExecute()
    {
        var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
        if (window != null)
        {
            window.Close();
        }
        // get comments and pass back to main window
    }

只需通過控件上的屬性公開值:

public string TheValue
{
    get { return theTextBox.Text; }
}

並從顯示對話框的位置閱讀它:

window.ShowDialog();
string value = control.TheValue;

(不確定為什么標記了問題“ MVVM”,因為您發布的代碼似乎不遵循MVVM模式)

您正在使用ShowDialog ,但沒有使用它的任何出色功能...

在顯示對話框的類中:

if (window.ShowDialog() && window.DialogResult.Value == true)
{
    //Access the properties on the window that hold your data.
}

然后在對話框本身中:

if (window != null)
{
    this.DialogResult = true;
    //Set the properties to the data you want to pass back.
    window.Close();
}

暫無
暫無

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

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