2017-08-17 63 views
0

Iam使用帶有MVVM模式的WPF。我想從viewmodel關閉一個窗口。我試圖使用一些以前的問題的解決方案,但它不起作用。如何關閉視圖模型在mvvm中的視圖?

這裏是我的代碼:

視圖模型:

//Defining commands  
public RelayCommand SaveAddBankCommand { get; private set; } 

//Constructor 
     public AddBankVM() 
     { 
      //Initializing Commands 
      SaveAddBankCommand = new RelayCommand(SaveAddBank); 
     } 

//Commands methods 
     public void SaveAddBank(object parameter) 
     { 
      new Banks().AddBank(this.BankName, _Status, System.Convert.ToDouble(Credit), this.Notes); 
      new Done("Bank has been added successfully."); 

      //here i want to close the window. 

     } 

視圖類:

public partial class AddBankView : Window 
    { 
     public AddBankView() 
     { 
      InitializeComponent(); 
      var addBankVM = new AddBankVM(); 
      this.DataContext = addBankVM; 
     } 
} 
+0

有很多方法可以做到這一點。你需要提供一些代碼來向我們展示你爲什麼要這樣做。然後我們可以幫助你。 – AQuirky

+0

我編輯了這個問題。你可以看看我的代碼。 –

+0

你在你的ViewModel中有一個窗口的實例,所以只需要執行'yourWindow.Close();' – Sach

回答

0

確定。下面是做這件事的方法之一:

在視圖模型...

//Commands methods 
    public void SaveAddBank() 
    { 
     new Banks().AddBank(this.BankName, _Status, System.Convert.ToDouble(Credit), this.Notes); 
     new Done("Bank has been added successfully."); 

     //here i want to close the window. 
     CloseWindowEvent?.Invoke(this, EventArgs.Empty); 
    } 
    public event EventHandler CloseWindowEvent; 

在後面的初始化代碼...

 InitializeComponent(); 
     DataContext = new AddBankVM(); 
     (DataContext as AddBankVM).CloseWindowEvent += CommandBench_CloseWindowEvent; 

最後,在後面的代碼的事件處理程序。 ..

private void CommandBench_CloseWindowEvent(object sender, EventArgs e) 
    { 
     Close(); 
    } 

從概念上講,發生的事情是視圖模型正在向窗口發送事件以關閉自身。

我懷疑MVVM風格的警察會有這個方法的一些問題。讓我們看看我們是否聽到他們的消息。

0

最簡單的方法是引入接口:

public interface IClosable 
{ 
    void Close(); 
} 

然後,你需要改變唯一代碼隱藏是指定窗口實現IClosable

public partial class MainWindow : Window, IClosable 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 
} 

The XAML:

<Button Width="50" 
      Height="20" 
      Command="{Binding CloseCommand}" 
      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                     AncestorType={x:Type Window}}}" 
      Content="Close" /> 

視圖模型:

#region Commands 
    public DelegateCommand<IClosable> CloseCommand => new DelegateCommand<IClosable>(Close, CanClose); 

    private bool CanClose(IClosable parameter) 
    { 
     return true; 
    } 
    private void Close(IClosable parameter) 
    { 
     var closable = parameter as IClosable; 
     if (closable != null) 
     { 
      closable.Close(); 
     } 
    } 

或者,您也可以使用EventTigger,或行爲,或附加的行爲,但它是那麼簡單,恕我直言。