Home >Backend Development >C++ >How to Close a WPF Form from the ViewModel in MVVM?
In WPF's MVVM design pattern, a common challenge is how to close a view (e.g., a form) from the ViewModel. ViewModel is usually responsible for managing business logic, while views are responsible for user interface (UI) display.
By design, ViewModel should not have direct knowledge of the View. This ensures separation of concerns and allows UI independence. However, closing the form requires access to the view, which can be a problem.
Traditional CodeBehind method: This involves placing the code to close the form in the view's codebehind file. This violates the MVVM pattern and introduces coupling between the view and the ViewModel.
Additional properties with style triggers: You can define an attached property on a form and use a style trigger to close the form when the attached property is set. While this solution adheres to MVVM principles, it involves extra code and can be cumbersome.
You can create a custom attached property called DialogCloser to simplify this process. This property takes a bool? parameter that represents the form's DialogResult. When the value of this property is set, it automatically sets the DialogResult property of the Window object containing the form.
<code class="language-csharp">public static class DialogCloser { public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached( "DialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(DialogResultChanged)); private static void DialogResultChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = d as Window; if (window != null) window.DialogResult = e.NewValue as bool?; } public static void SetDialogResult(Window target, bool? value) { target.SetValue(DialogResultProperty, value); } }</code>
To use this attribute, just apply it to the Window element in your XAML view:
<code class="language-xml"><Window ... xc:DialogCloser.DialogResult="{Binding DialogResult}" xmlns:xc="clr-namespace:ExCastle.Wpf"></Window></code>
In the ViewModel, bind the DialogResult property to a Boolean property:
<code class="language-csharp">public class MyViewModel : INotifyPropertyChanged { ... private bool? _dialogResult; public bool? DialogResult { get { return _dialogResult; } set { _dialogResult = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DialogResult))); } } ... }</code>
When the DialogResult property is set in a ViewModel, the DialogCloser attached property automatically updates the DialogResult of the containing Window object, effectively closing the form.
The above is the detailed content of How to Close a WPF Form from the ViewModel in MVVM?. For more information, please follow other related articles on the PHP Chinese website!