How to open a new window using MVVM Light Toolkit

后端 未结 6 899
青春惊慌失措
青春惊慌失措 2020-11-27 11:50

I am using MVVM Light toolkit in my WPF application. I would like to know what is the best approach for opening a new window from an existing window. I have got this M

6条回答
  •  孤独总比滥情好
    2020-11-27 12:09

    I find the best way to approach this, is opening and closing the window from the ViewModel. As this link suggests,

    1. Create a DialogCloser class
        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.Close();
            }
    
            public static void SetDialogResult(Window target, bool? value)
            {
                target.SetValue(DialogResultProperty, value);
            }
        }
    
    1. Create a Base ViewModel inheriting from GalaSoft.MvvmLight.ViewModelBase with there additional members. Once done, use this viewmodel as base for other viewmodels.
        bool? _closeWindowFlag;
        public bool? CloseWindowFlag
        {
            get { return _closeWindowFlag; }
            set
            {
                _closeWindowFlag = value;
                RaisePropertyChanged("CloseWindowFlag");
            }
        }
    
        public virtual void CloseWindow(bool? result = true)
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, 
            new Action(() =>
            {
                CloseWindowFlag = CloseWindowFlag == null ? true : !CloseWindowFlag;
            }));
        }
    1. In the view, Bind the DialogCloser.DialogResult dependency property with the CloseWindowFlag property in the base viewmodel.

    Then you can open/close/hide the window from the viewmodel.

提交回复
热议问题