我正在尝试在窗口对话框关闭后获取值:
public partial class MyDialogWindow: Window
{
public string selectedItem = "";
public MyDialogWindow(string selectedItem)
{
InitializeComponent();
this.selectedItem = selectedItem;
}
...
}
// To call dialog
string result = "";
MyDialogWindow dialog = new MyDialogWindow(result);
if (form.ShowDialog().Value)
{
string res = result;
}
但'结果'总是空的。在winforms我可以得到这个结果,但在WPF中没有。那么如何在关闭后从窗口返回结果?
答案 0 :(得分:6)
字符串不像C#中那样工作 - 它们是不可变的。
您可以像其他人建议的那样使用ref
关键字来实现此功能,但是这只有在构造函数中设置SelectedItem
时才有效,这有点不太可能!
执行此操作的常规方法是让对话框在对话框中显示属性:
public partial class MyDialogWindow: Window
{
public string SelectedItem
{
get;
set;
{
// etc...
}
MyDialogWindow dialog = new MyDialogWindow(result);
if (form.ShowDialog().Value)
{
string res = dialog.SelectedItem;
}
这是其他对话框(例如打开/保存文件对话框)的工作方式。
答案 1 :(得分:1)
将公共属性添加到MyDialogWindow
类,然后在返回ShowDialog()后访问它。
class MyDialogWindow
{
public string UserEnteredData { get; set; }
}
if (form.ShowDialog().Value)
{
string res = dialog.UserEnteredData;
}
答案 2 :(得分:1)
这是我刚写的示例窗口:
public partial class ActionDialog : Window
{
public ActionDialog(string msg)
{
InitializeComponent();
MsgTbx.Text = msg;
}
//Record the user's click result
public bool ClickResult = false;
//In Other place need to use this Dialog just Call this Method
public static bool EnsureExecute(string msg)
{
ActionDialog dialogAc = new ActionDialog(msg);
//this line will run through only when dialogAc is closed
dialogAc.ShowDialog();
//the magic is the property ClickResult of dialogAc
//can be accessed even when it's closed
return dialogAc.ClickResult;
}
//add this method to your custom OK Button's click event
private void Execute_OnClick(object sender, RoutedEventArgs e)
{
ClickResult = true;
this.Close();
}
//add this method to your custom Cancel Button click event
private void Cancel_OnClick(object sender, RoutedEventArgs e)
{
ClickResult = false;
this.Close();
}
}
调用Dialog时的代码:
//simply one line can get the user's Button Click Result
bool isExecute = ActionDialog.EnsureExecute(msg);
参考