Reputation: 5909
I'm trying to get value after window dialog is closed:
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;
}
But 'result' always is empty. In winforms I can get this result, but in WPF not. So How to return result from window, after it is closed?
Upvotes: 3
Views: 15868
Reputation: 7181
Here's an Example Window I just write:
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();
}
}
And the code when calling the Dialog:
//simply one line can get the user's Button Click Result
bool isExecute = ActionDialog.EnsureExecute(msg);
Reference to
Upvotes: 4
Reputation: 86789
Strings don't work like that in C# - they are immutable.
You could get this to work using the ref
keyword as other people have suggested, however this will only work if you set SelectedItem
in the constructor, which is a bit unlikely!
The normal way of doing this is to have your dialog expose a property on your dialog:
public partial class MyDialogWindow: Window
{
public string SelectedItem
{
get;
set;
{
// etc...
}
MyDialogWindow dialog = new MyDialogWindow(result);
if (form.ShowDialog().Value)
{
string res = dialog.SelectedItem;
}
This is the way that other dialogs (such as the open / save file dialogs) work.
Upvotes: 6
Reputation: 62564
Add public property to the MyDialogWindow
class and then just access it after the ShowDialog() was returned.
class MyDialogWindow
{
public string UserEnteredData { get; set; }
}
if (form.ShowDialog().Value)
{
string res = dialog.UserEnteredData;
}
Upvotes: 1