1. 程式人生 > >wpf mvvm模式下 在ViewModel關閉view

wpf mvvm模式下 在ViewModel關閉view

ret init .cn lose cnblogs ref 源碼 參數 loaded

本文只是博主用來記錄筆記,誤噴

使用到到了MVVM中消息通知功能

第一步:在需要關閉窗體中註冊消息

 

 1 public UserView()
 2         {
 3             this.DataContext = new UserViewModel();
 4             InitializeComponent();
 5             //註冊消息
 6             Messenger.Default.Register<string>(this,"closeUserView", FunClos);
 7
//移除消息 8 Unloaded += (sender, e) => Messenger.Default.Unregister<string>(this, "closeUserView"); 9 } 10 11 private void FunClos(string msg) 12 { 13 MessageBox.Show(msg); 14 this.Close(); 15 }

為什麽需要移除消息是因為註冊消息相當註冊了一個全局變量,當註冊後需要及時清除

Register:方法中參數意思分別是 
        1:執行對象
        2:口令
        3:需要執行的方法
第二步:在ViewModel中寫發送口令方法
 
 1 private RelayCommand _closeWindowCommand;
 2         public RelayCommand CloseWindowCommand
 3         {
 4             get
 5             {
 6                 if (_closeWindowCommand == null)
 7                 {
8 _closeWindowCommand = new RelayCommand(() => 9 { 10 Messenger.Default.Send<string>("這是一條來自ViewModel Message", "closeUserView"); 11 }); 12 } 13 return _closeWindowCommand; 14 } 15 }

到這裏就完成了在ViewModel中關閉指定窗體,當然也可以使用此方法打開指定窗體

好處:降低耦合度

源碼




wpf mvvm模式下 在ViewModel關閉view