2016-11-24 60 views
1

如何将窗口设置为从ViewModel声明,初始化并打开的所有者?如何从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; 

如何从视图模型实现的呢?

+0

你可以尝试结合它到您ViewModel中的一个Window,并且从您VM中将Window设置为任何相关的。 但是,你通常希望你ViewModel不知道你的视图,所以我不知道这将是一个干净的方式。 – Belterius

回答

3

说实话,我不会做任何与在ViewModel中显示窗口有关的东西。你可以做的事情是发送一条消息(例如使用MVVMLight的Messenger服务)到视图,在那里你可以做显示和设置所有者shinanigaz

1

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; 
     } 
    } 
} 
相关问题