I want to show a window to create an object based on a form my users fill.
What I do now is from my main view model, I instanciate my form window, set its datacontext to a new instance of the corresponding viewmodel class and get ShowDialog()
var addLicWnd = new AddLicenseWindow();
if (addLicWnd.ShowDialog() ?? false)
{
var x = ((AddLicenseWindowViewModel)addLicWnd.DataContext).dialogResult;
//dialogResult is a property I set in my VM to get the data back when the form closes
}
This ViewModel exposes a dialogResult property to get the data back from the form to my main ViewModel where I will then add it in DB etc ...
My problem here is I cannot close the form within it from a button press for example.
What I found is an answer from a similar question ( https://stackoverflow.com/a/3329467/9734355 ) But the only way I found to use it is to call this SetDialogResult method which takes the window as a parameter. Which means I need to have a reference to my View inside my ViewModel, hence breaking MVVM (or did I miss something?)
So it would look like
Main ViewModel
var addLicWnd = new AddLicenseWindow();
addLicWnd.Datacontext = new AddLicenseWindowViewModel(addLicWnd);
if (addLicWnd.ShowDialog() ?? false)
{
var x = ((AddLicenseWindowViewModel)addLicWnd.DataContext).dialogResult;
}
Form ViewModel
public Window window;
public event PropertyChangedEventHandler PropertyChanged;
public LicenseRecordModel dialogResult;
//Commands and OnPropertyChanged...
public AddLicenseWindowViewModel(Window w)
{
window = w;
}
private void ButtonClick(){
dialogResult = new LicenseRecordModel("b", "b", "b", "b", "b");
//...
DialogCloser.SetDialogResult(wnd, true);
}
This works but does not look MVVM compliant to me, what should I do? Did I misunderstand the answer?