Tomtom
Tomtom

Reputation: 9394

MVVM Get value from closed window

I have a small Dialog where i can set a value. The View of this Dialog has just one TextBox and two buttons. I am binding the textbox.Text to a property TbText in the ViewModel. Through a behavior i close the view from it's viewmodel. The code to open this dialog looks like:

AddLineDialog dialog = new AddLineDialog();
bool? result = dialog.ShowDialog();
if(result.HasValue && result.Value)
{
//Here i need the Text from the closed dialog
}
...

After the Dialog is closed i need to access the value of the Property TbText. How can i achive this?

Upvotes: 0

Views: 1260

Answers (2)

Smaug
Smaug

Reputation: 2673

Use INotifyPropertyChanged interface in the Source, then in the textbox binding should be like below

<TextBox Text={Binding Path=Name, 
                            Mode=TwoWay, 
                            UpdateSourceTrigger=PropertyChanged} />

It was a two way binding so whenever the user enter the data which updated in the source propery also. If you need this data you can access from the model property which you use to bind.

Hope the above solution helps you to solve your problem

Upvotes: 0

JMan
JMan

Reputation: 2629

You can bind a ViewModel or any class to the Dialog's Datacontext:

    AddLineDialog dialog = new AddLineDialog();
    var vm = new LineDialogViewModel();
    dialog.DataContext = vm;

Then bind the textbox to a property from your class

    <textbox Value="{Binding MyProperty}">

After this you can read out your class

    if(dialog.ShowDialog())
    {
       var value = vm.MyProperty;
    }

Upvotes: 3

Related Questions