Passing Data From One Window To Another in WPF
Good afternoon everyone!
When passing data from one window to another in WPF, the ideal approach is to set the both window's DataContext properties with the same ViewModel. In such a way, if a property in a View Model is updated in window1, window2 can access that property and the new value that has reflected. The snippet below show a child window and set's it's DataContext property using the main window's DataContext property. So whatever changes happen to a view model's property value, main window can also get a copy of that new value.
When passing data from one window to another in WPF, the ideal approach is to set the both window's DataContext properties with the same ViewModel. In such a way, if a property in a View Model is updated in window1, window2 can access that property and the new value that has reflected. The snippet below show a child window and set's it's DataContext property using the main window's DataContext property. So whatever changes happen to a view model's property value, main window can also get a copy of that new value.
public void ShowWindow(Window childWindow, bool isDialog) { //Application.Current.Windows[0] is the main window //set DataContext of child window with DataContext of main window var vm = Application.Current.Windows[0].DataContext; if (childWindow != null) { childWindow.DataContext = vm; if (isDialog) childWindow.ShowDialog(); else childWindow.Show(); } }
Comments
Post a Comment