簡體   English   中英

如何從 WPF 中的 ViewModel 將窗口設置為所有者

[英]How to set a window as owner from ViewModel in WPF

如何將窗口設置為從 ViewModel 聲明、初始化和打開的所有者?

這是代碼:

public class ViewModel : INotifyPropertyChanged

{
  // declaration
  static nextWindow nw;
  ...

  public ICommand OpenNextWindow { get { return new RelayCommand(OpenNextWindowExecute, CanOpenNextWindowExecute); } }

  bool CanOpenNextWindowExecute(object parameter)
  {
      return true;
  }

  void OpenNextWindowExecute(object parameter)
  {
      nw = new nextWindow();
      nw.WindowStartupLocation = WindowStartupLocation.CenterScreen;
      // Set this window as owner before showing it...
      nw.Show();
  }
 }

在 nextWindow 的代碼隱藏文件中,我可以使用以下代碼將 nextWindow 設置為所有者:

nw.Owner = this;

我怎樣才能從視圖模型中實現它?

老實說,我不會做任何與在 ViewModel 中顯示窗口相關的事情。 不過,您可以做的是向視圖發送消息(例如使用 MVVMLight 的 Messenger 服務),您可以在其中進行表演並設置所有者 shinanigaz

MVVM 背后的整個想法是,您希望視圖和業務邏輯之間完全分離,從而實現更好的維護、可擴展性、測試等。因此,您的視圖模型應該幾乎始終不知道任何視圖的存在。

因此,使用視圖或某些視圖處理程序可以偵聽的信使服務,然后決定是否要處理消息。 因此讓視圖處理程序決定接下來調用哪個其他視圖或顯示哪個消息框。

有很多可用的選項,但正如@Oyiwai 所說,MVVMLight 的 Messenger 服務快速且易於使用。

在您的包管理器控制台中運行 install-package MvvmLightLibs。 MvvmLightLibs 還有一個額外的好處,因為它已經有一個 INotifyPropertyChanged 的​​實現,我看到你已經實現了。

請注意,這是一個快速示例。 我不建議使用 case 語句,因為我在這里對他查看的名稱進行了硬編碼。

創建一個 WindowMessage 類..

public class RaiseWindowMessage
{
    public string WindowName { get; set; }
    public bool ShowAsDialog { get; set; }
}

在您的視圖模型中

public class ViewModel : ViewModelBase
{
    public RelayCommand<string> RaiseWindow => new RelayCommand<string>(raiseWindow, canRaiseWindow);

    private bool canRaiseWindow(string nextWindowName)
    {
        // some logic
        return true;
    }

    private void raiseWindow(string nextWindowName)
    {
        RaiseWindowMessage message = new RaiseWindowMessage();
        message.WindowName = nextWindowName;
        message.ShowAsDialog = true;

        MessengerInstance.Send<RaiseWindowMessage>(message);
    }
}

在您的視圖中或最好在某些視圖處理程序類中..

public class ViewHandler
{
    public ViewHandler()
    {
        Messenger.Default.Register<RaiseWindowMessage>(this, raiseNextWindow);
    }        

    private void raiseNextWindow(RaiseWindowMessage obj)
    {
        // determine which window to raise and show it
        switch (obj.WindowName)
        {
            case "NextWindow":
                NextWindow view = new NextWindow();
                if (obj.ShowAsDialog)
                    view.ShowDialog();
                else
                    view.Show();
                break;
            // some other case here...
            default:
                break;
        }
    }
}
nw.Owner = Application.Current.MainWindow;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM