110

我使用 a 创建登录window control以允许用户登录到WPF我正在创建的应用程序。

到目前为止,我已经创建了一个方法来检查用户是否在登录屏幕上的ausernamepassworda中输入了正确的凭据,两个.textboxbindingproperties

我通过创建一个bool方法来实现这一点,就像这样;

public bool CheckLogin()
{
    var user = context.Users.Where(i => i.Username == this.Username).SingleOrDefault();

    if (user == null)
    {
        MessageBox.Show("Unable to Login, incorrect credentials.");
        return false;
    }
    else if (this.Username == user.Username || this.Password.ToString() == user.Password)
    {
        MessageBox.Show("Welcome " + user.Username + ", you have successfully logged in.");

        return true;
    }
    else
    {
        MessageBox.Show("Unable to Login, incorrect credentials.");
        return false;
    }
}

public ICommand ShowLoginCommand
{
    get
    {
        if (this.showLoginCommand == null)
        {
            this.showLoginCommand = new RelayCommand(this.LoginExecute, null);
        }
        return this.showLoginCommand;
    }
}

private void LoginExecute()
{
    this.CheckLogin();
} 

我也有一个commandbind到我的按钮内的xaml类似这样的;

<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding ShowLoginCommand}" />

当我输入用户名和密码时,它会执行适当的代码,无论是对还是错。但是,当用户名和密码都正确时,如何从 ViewModel 关闭此窗口?

我之前尝试过使用 adialog modal但效果不佳。此外,在我的 app.xaml 中,我做了类似以下的操作,它首先加载登录页面,然后一旦为真,加载实际的应用程序。

private void ApplicationStart(object sender, StartupEventArgs e)
{
    Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

    var dialog = new UserView();

    if (dialog.ShowDialog() == true)
    {
        var mainWindow = new MainWindow();
        Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
        Current.MainWindow = mainWindow;
        mainWindow.Show();
    }
    else
    {
        MessageBox.Show("Unable to load application.", "Error", MessageBoxButton.OK);
        Current.Shutdown(-1);
    }
}

问题:如何Window control从 ViewModel 关闭登录?

提前致谢。

4

18 回答 18

173

您可以使用CommandParameter. 请参阅下面的示例。

我已经实现了一个CloseWindow将 Windows 作为参数并关闭它的方法。窗口通过 传递给 ViewModel CommandParameter。请注意,您需要为x:Name应该关闭的窗口定义一个。在我的 XAML 窗口中,我通过调用此方法Command并将窗口本身作为参数传递给 ViewModel,使用CommandParameter.

Command="{Binding CloseWindowCommand, Mode=OneWay}" 
CommandParameter="{Binding ElementName=TestWindow}"

视图模型

public RelayCommand<Window> CloseWindowCommand { get; private set; }

public MainViewModel()
{
    this.CloseWindowCommand = new RelayCommand<Window>(this.CloseWindow);
}

private void CloseWindow(Window window)
{
    if (window != null)
    {
       window.Close();
    }
}

看法

<Window x:Class="ClientLibTestTool.ErrorView"
        x:Name="TestWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:localization="clr-namespace:ClientLibTestTool.ViewLanguages"
        DataContext="{Binding Main, Source={StaticResource Locator}}"
        Title="{x:Static localization:localization.HeaderErrorView}"
        Height="600" Width="800"
        ResizeMode="NoResize"
        WindowStartupLocation="CenterScreen">
    <Grid> 
        <Button Content="{x:Static localization:localization.ButtonClose}" 
                Height="30" 
                Width="100" 
                Margin="0,0,10,10" 
                IsCancel="True" 
                VerticalAlignment="Bottom" 
                HorizontalAlignment="Right" 
                Command="{Binding CloseWindowCommand, Mode=OneWay}" 
                CommandParameter="{Binding ElementName=TestWindow}"/>
    </Grid>
</Window>

请注意,我使用的是 MVVM 轻框架,但主体适用于每个 wpf 应用程序。

这个解决方案违反了 MVVM 模式,因为视图模型不应该知道关于 UI 实现的任何事情。如果要严格遵循 MVVM 编程范式,则必须使用接口抽象视图的类型。

MVVM 符合解决方案(前 EDIT2)

用户Crono在评论部分提到了一个有效点:

将 Window 对象传递给视图模型会破坏 MVVM 模式恕我直言,因为它会强制您的 vm 知道正在查看它的内容。

您可以通过引入包含 close 方法的接口来解决此问题。

界面:

public interface ICloseable
{
    void Close();
}

您重构的 ViewModel 将如下所示:

视图模型

public RelayCommand<ICloseable> CloseWindowCommand { get; private set; }

public MainViewModel()
{
    this.CloseWindowCommand = new RelayCommand<IClosable>(this.CloseWindow);
}

private void CloseWindow(ICloseable window)
{
    if (window != null)
    {
        window.Close();
    }
}

您必须在视图中引用并实现ICloseable接口

查看(后面的代码)

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

回答原问题:(前EDIT1)

您的登录按钮(添加了 CommandParameter):

<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding ShowLoginCommand}" CommandParameter="{Binding ElementName=LoginWindow}"/>

你的代码:

 public RelayCommand<Window> CloseWindowCommand { get; private set; } // the <Window> is important for your solution!

 public MainViewModel() 
 {
     //initialize the CloseWindowCommand. Again, mind the <Window>
     //you don't have to do this in your constructor but it is good practice, thought
     this.CloseWindowCommand = new RelayCommand<Window>(this.CloseWindow);
 }

 public bool CheckLogin(Window loginWindow) //Added loginWindow Parameter
 {
    var user = context.Users.Where(i => i.Username == this.Username).SingleOrDefault();

    if (user == null)
    {
        MessageBox.Show("Unable to Login, incorrect credentials.");
        return false;
    }
    else if (this.Username == user.Username || this.Password.ToString() == user.Password)
    {
        MessageBox.Show("Welcome "+ user.Username + ", you have successfully logged in.");
        this.CloseWindow(loginWindow); //Added call to CloseWindow Method
        return true;
    }
    else
    {
        MessageBox.Show("Unable to Login, incorrect credentials.");
        return false;
    }
 }

 //Added CloseWindow Method
 private void CloseWindow(Window window)
 {
     if (window != null)
     {
         window.Close();
     }
 }
于 2013-04-24T14:56:25.413 回答
49

当我需要这样做时,我通常会在视图模型上放置一个事件,然后Window.Close()在将视图模型绑定到窗口时将其连接到

public class LoginViewModel
{
    public event EventHandler OnRequestClose;

    private void Login()
    {
        // Login logic here
        OnRequestClose(this, new EventArgs());
    }
}

并且在创建登录窗口时

var vm = new LoginViewModel();
var loginWindow = new LoginWindow
{
    DataContext = vm
};
vm.OnRequestClose += (s, e) => loginWindow.Close();

loginWindow.ShowDialog(); 
于 2013-04-23T15:37:54.873 回答
38

保持 MVVM,我认为使用 Blend SDK (System.Windows.Interactivity) 中的行为或 Prism 的自定义交互请求对于这种情况非常有效。

如果走行为路线,这是一般的想法:

public class CloseWindowBehavior : Behavior<Window>
{
    public bool CloseTrigger
    {
        get { return (bool)GetValue(CloseTriggerProperty); }
        set { SetValue(CloseTriggerProperty, value); }
    }

    public static readonly DependencyProperty CloseTriggerProperty =
        DependencyProperty.Register("CloseTrigger", typeof(bool), typeof(CloseWindowBehavior), new PropertyMetadata(false, OnCloseTriggerChanged));

    private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = d as CloseWindowBehavior;

        if (behavior != null)
        {
            behavior.OnCloseTriggerChanged();
        }
    }

    private void OnCloseTriggerChanged()
    {
        // when closetrigger is true, close the window
        if (this.CloseTrigger)
        {
            this.AssociatedObject.Close();
        }
    }
}

然后在您的窗口中,您只需将 CloseTrigger 绑定到一个布尔值,当您希望窗口关闭时将设置该值。

<Window x:Class="TestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:local="clr-namespace:TestApp"
        Title="MainWindow" Height="350" Width="525">
    <i:Interaction.Behaviors>
        <local:CloseWindowBehavior CloseTrigger="{Binding CloseTrigger}" />
    </i:Interaction.Behaviors>

    <Grid>

    </Grid>
</Window>

最后,当您希望窗口像这样关闭时,您的 DataContext/ViewModel 将具有您设置的属性:

public class MainWindowViewModel : INotifyPropertyChanged
{
    private bool closeTrigger;

    /// <summary>
    /// Gets or Sets if the main window should be closed
    /// </summary>
    public bool CloseTrigger
    {
        get { return this.closeTrigger; }
        set
        {
            this.closeTrigger = value;
            RaisePropertyChanged(nameof(CloseTrigger));
        }
    }

    public MainWindowViewModel()
    {
        // just setting for example, close the window
        CloseTrigger = true;
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

(设置你的 Window.DataContext = new MainWindowViewModel())

于 2013-04-24T01:49:10.653 回答
26

可能晚了,但这是我的答案

foreach (Window item in Application.Current.Windows)
{
    if (item.DataContext == this) item.Close();
}
于 2017-09-30T14:45:13.470 回答
14

那么这是我在几个项目中使用的东西。它可能看起来像一个黑客,但它工作正常。

public class AttachedProperties : DependencyObject //adds a bindable DialogResult to window
{
    public static readonly DependencyProperty DialogResultProperty = 
        DependencyProperty.RegisterAttached("DialogResult", typeof(bool?), typeof(AttachedProperties), 
        new PropertyMetaData(default(bool?), OnDialogResultChanged));

    public bool? DialogResult
    {
        get { return (bool?)GetValue(DialogResultProperty); }
        set { SetValue(DialogResultProperty, value); }
    }

    private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var window = d as Window;
        if (window == null)
            return;

        window.DialogResult = (bool?)e.NewValue;
    }
}

现在您可以绑定DialogResult到 VM 并设置其属性值。Window设置值时将关闭。

<!-- Assuming that the VM is bound to the DataContext and the bound VM has a property DialogResult -->
<Window someNs:AttachedProperties.DialogResult={Binding DialogResult} />

这是在我们的生产环境中运行的摘要

<Window x:Class="AC.Frontend.Controls.DialogControl.Dialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:DialogControl="clr-namespace:AC.Frontend.Controls.DialogControl" 
        xmlns:hlp="clr-namespace:AC.Frontend.Helper"
        MinHeight="150" MinWidth="300" ResizeMode="NoResize" SizeToContent="WidthAndHeight"
        WindowStartupLocation="CenterScreen" Title="{Binding Title}"
        hlp:AttachedProperties.DialogResult="{Binding DialogResult}" WindowStyle="ToolWindow" ShowInTaskbar="True"
        Language="{Binding UiCulture, Source={StaticResource Strings}}">
        <!-- A lot more stuff here -->
</Window>

如您所见,我xmlns:hlp="clr-namespace:AC.Frontend.Helper"先声明命名空间,然后再声明 binding hlp:AttachedProperties.DialogResult="{Binding DialogResult}"

AttachedProperty外观是这样的。这与我昨天发布的不一样,但恕我直言,它不应该有任何影响。

public class AttachedProperties
{
    #region DialogResult

    public static readonly DependencyProperty DialogResultProperty =
        DependencyProperty.RegisterAttached("DialogResult", typeof (bool?), typeof (AttachedProperties), new PropertyMetadata(default(bool?), OnDialogResultChanged));

    private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var wnd = d as Window;
        if (wnd == null)
            return;

        wnd.DialogResult = (bool?) e.NewValue;
    }

    public static bool? GetDialogResult(DependencyObject dp)
    {
        if (dp == null) throw new ArgumentNullException("dp");

        return (bool?)dp.GetValue(DialogResultProperty);
    }

    public static void SetDialogResult(DependencyObject dp, object value)
    {
        if (dp == null) throw new ArgumentNullException("dp");

        dp.SetValue(DialogResultProperty, value);
    }

    #endregion
}
于 2013-04-23T15:11:59.967 回答
13

简单的方法

public interface IRequireViewIdentification
{
    Guid ViewID { get; }
}

实现到 ViewModel

public class MyViewVM : IRequireViewIdentification
{
    private Guid _viewId;

    public Guid ViewID
    {
        get { return _viewId; }
    }

    public MyViewVM()
    {
        _viewId = Guid.NewGuid();
    }
}

添加通用窗口管理器助手

public static class WindowManager
{
    public static void CloseWindow(Guid id)
    {
        foreach (Window window in Application.Current.Windows)
        {
            var w_id = window.DataContext as IRequireViewIdentification;
            if (w_id != null && w_id.ViewID.Equals(id))
            {
                window.Close();
            }
        }
    }
}

并在视图模型中像这样关闭它

WindowManager.CloseWindow(ViewID);
于 2014-12-28T13:28:46.863 回答
5

我知道这是一篇旧帖子,可能没有人会滚动这么远,我知道我没有。所以,经过几个小时的尝试不同的东西,我找到了这个博客,老兄把它杀了。最简单的方法,尝试了它,它就像一个魅力。

博客

在视图模型中:

...

public bool CanClose { get; set; }

private RelayCommand closeCommand;
public ICommand CloseCommand
{
    get
    {
        if(closeCommand == null)
        (
            closeCommand = new RelayCommand(param => Close(), param => CanClose);
        )
    }
}

public void Close()
{
    this.Close();
}

...

向 ViewModel 添加一个 Action 属性,但从 View 的代码隐藏文件中定义它。这将让我们在 ViewModel 上动态定义一个指向 View 的引用。

在 ViewModel 上,我们将简单地添加:

public Action CloseAction { get; set; }

在视图上,我们将其定义为:

public View()
{
    InitializeComponent() // this draws the View
    ViewModel vm = new ViewModel(); // this creates an instance of the ViewModel
    this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
    if ( vm.CloseAction == null )
        vm.CloseAction = new Action(() => this.Close());
}
于 2019-02-08T21:17:24.763 回答
4

这是一个使用 MVVM Light Messenger 而不是事件的简单示例。单击按钮时,视图模型会发送关闭消息:

    public MainViewModel()
    {
        QuitCommand = new RelayCommand(ExecuteQuitCommand);
    }

    public RelayCommand QuitCommand { get; private set; }

    private void ExecuteQuitCommand() 
    {
        Messenger.Default.Send<CloseMessage>(new CloseMessage());
    }

然后在窗口后面的代码中接收它。

    public Main()
    {   
        InitializeComponent();
        Messenger.Default.Register<CloseMessage>(this, HandleCloseMessage);
    }

    private void HandleCloseMessage(CloseMessage closeMessage)
    {
        Close();
    }
于 2016-09-02T13:05:08.730 回答
4

这个怎么样?

视图模型:

class ViewModel
{
    public Action CloseAction { get; set; }
    private void Stuff()
    {
       // Do Stuff
       CloseAction(); // closes the window
    }
}

在您的 ViewModel 中使用 CloseAction() 关闭窗口,就像上面的示例一样。

看法:

public View()
{
    InitializeComponent();
    ViewModel vm = new ViewModel (); // this creates an instance of the ViewModel
    this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
    if (vm.CloseAction == null)
        vm.CloseAction = new Action(() => this.Close());
}
于 2017-05-09T08:39:41.527 回答
2

您可以像这样在 ViewModel 中创建新的事件处理程序。

public event EventHandler RequestClose;

    protected void OnRequestClose()
    {
        if (RequestClose != null)
            RequestClose(this, EventArgs.Empty);
    }

然后为 ExitCommand 定义 RelayCommand。

private RelayCommand _CloseCommand;
    public ICommand CloseCommand
    {
        get
        {
            if(this._CloseCommand==null)
                this._CloseCommand=new RelayCommand(CloseClick);
            return this._CloseCommand;
        }
    }

    private void CloseClick(object obj)
    {
        OnRequestClose();
    }

然后在 XAML 文件集中

<Button Command="{Binding CloseCommand}" />

在 xaml.cs 文件中设置 DataContext 并订阅我们创建的事件。

public partial class MainWindow : Window
{
    private ViewModel mainViewModel = null;
    public MainWindow()
    {
        InitializeComponent();
        mainViewModel = new ViewModel();
        this.DataContext = mainViewModel;
        mainViewModel.RequestClose += delegate(object sender, EventArgs args) { this.Close(); };
    }
}
于 2016-01-20T08:52:20.027 回答
1

我提供的方法是在 ViewModel 中声明事件并使用混合 InvokeMethodAction,如下所示。

示例视图模型

public class MainWindowViewModel : BindableBase, ICloseable
{
    public DelegateCommand SomeCommand { get; private set; }
    #region ICloseable Implementation
    public event EventHandler CloseRequested;        

    public void RaiseCloseNotification()
    {
        var handler = CloseRequested;
        if (handler != null)
        {
            handler.Invoke(this, EventArgs.Empty);
        }
    }
    #endregion

    public MainWindowViewModel()
    {
        SomeCommand = new DelegateCommand(() =>
        {
            //when you decide to close window
            RaiseCloseNotification();
        });
    }
}

I Closeable 界面如下,但不需要执行此操作。ICloseable 将有助于创建通用视图服务,因此如果您通过依赖注入构造视图和 ViewModel,那么您可以做的是

internal interface ICloseable
{
    event EventHandler CloseRequested;
}

使用 ICloseable

var viewModel = new MainWindowViewModel();
        // As service is generic and don't know whether it can request close event
        var window = new Window() { Content = new MainView() };
        var closeable = viewModel as ICloseable;
        if (closeable != null)
        {
            closeable.CloseRequested += (s, e) => window.Close();
        }

下面是Xaml,即使你不实现接口也可以使用这个xaml,它只需要你的视图模型来引发CloseRquested。

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFRx"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
xmlns:ViewModels="clr-namespace:WPFRx.ViewModels" x:Name="window" x:Class="WPFRx.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525" 
d:DataContext="{d:DesignInstance {x:Type ViewModels:MainWindowViewModel}}">

<i:Interaction.Triggers>
    <i:EventTrigger SourceObject="{Binding Mode=OneWay}" EventName="CloseRequested" >
        <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

<Grid>
    <Button Content="Some Content" Command="{Binding SomeCommand}" Width="100" Height="25"/>
</Grid>

于 2016-03-06T13:37:09.117 回答
1

您可以Messenger从 MVVMLight 工具包中使用。在您ViewModel发送这样的消息:
Messenger.Default.Send(new NotificationMessage("Close"));
然后在您的 Windows 代码后面,之后InitializeComponent,像这样注册该消息:

Messenger.Default.Register<NotificationMessage>(this, m=>{
    if(m.Notification == "Close") 
    {
        this.Close();
    }
   });

您可以在此处找到有关 MVVMLight 工具包的更多信息: Codeplex 上的 MVVMLight 工具包

请注意,MVVM 中没有“完全没有代码隐藏规则”,您可以在视图代码隐藏中注册消息。

于 2016-12-06T17:08:17.430 回答
0

这很简单。您可以为 Login 创建自己的 ViewModel 类 - LoginViewModel。您可以创建视图 var dialog = new UserView(); 在您的 LoginViewModel 中。并且您可以将 Command LoginCommand 设置为按钮。

<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding LoginCommand}" />

<Button Name="btnCancel" IsDefault="True" Content="Login" Command="{Binding CancelCommand}" />

视图模型类:

public class LoginViewModel
{
    Window dialog;
    public bool ShowLogin()
    {
       dialog = new UserView();
       dialog.DataContext = this; // set up ViewModel into View
       if (dialog.ShowDialog() == true)
       {
         return true;
       }

       return false;
    }

    ICommand _loginCommand
    public ICommand LoginCommand
    {
        get
        {
            if (_loginCommand == null)
                _loginCommand = new RelayCommand(param => this.Login());

            return _loginCommand;
        }
    }

    public void CloseLoginView()
    {
            if (dialog != null)
          dialog.Close();
    }   

    public void Login()
    {
        if(CheckLogin()==true)
        {
            CloseLoginView();         
        }
        else
        {
          // write error message
        }
    }

    public bool CheckLogin()
    {
      // ... check login code
      return true;
    }
}
于 2013-04-23T15:14:42.393 回答
0

这是我很简单的一种方式:

YourWindow.xaml.cs

//In your constructor
public YourWindow()
{
    InitializeComponent();
    DataContext = new YourWindowViewModel(this);
}

YourWindowViewModel.cs

private YourWindow window;//so we can kill the window

//In your constructor
public YourWindowViewModel(YourWindow window)
{
    this.window = window;
}

//to close the window
public void CloseWindow()
{
    window.Close();
}

我认为您选择的答案没有任何问题,我只是认为这可能是一种更简单的方法!

于 2014-07-08T21:58:55.770 回答
0

您可以将 window 视为服务(例如 UI 服务)并通过interface将自身传递给 viewmodel ,如下所示:

public interface IMainWindowAccess
{
    void Close(bool result);
}

public class MainWindow : IMainWindowAccess
{
    // (...)
    public void Close(bool result)
    {
        DialogResult = result;
        Close();
    }
}

public class MainWindowViewModel
{
    private IMainWindowAccess access;

    public MainWindowViewModel(IMainWindowAccess access)
    {
        this.access = access;
    }

    public void DoClose()
    {
        access.Close(true);
    }
}

该解决方案具有将视图本身传递给 viewmodel 而没有破坏 MVVM 的缺点,因为尽管将物理视图传递给 viewmodel,后者仍然不知道前者,它只看到一些IMainWindowAccess. 因此,例如,如果我们想将此解决方案迁移到其他平台,则只需IMainWindowAccessActivity.

我在这里发布解决方案是为了提出与事件不同的方法(尽管它实际上非常相似),因为它似乎比事件实现(附加/分离等)简单一点,但仍然与 MVVM 模式很好地对齐。

于 2019-11-07T08:45:41.727 回答
0

在 MVVM WPF 中,我通常将 View 设计为 UserControl。这只是你想如何显示它的问题。如果你希望它在一个窗口中,那么你可以做一个 WindowService 类:

public class WindowService
{
   //...

   public void Show_window(object viewModel, int height, int width, string title)
   {
     var window = new Window
     {
       Content = viewModel,
       Title = title,
       Height = height,
       Width = width,
       WindowStartupLocation = WindowStartupLocation.CenterOwner,
       Owner = Application.Current.MainWindow,
       Style = (Style)Application.Current.FindResource("Window_style") //even style can be added
      };

      //If you own custom window style, then you can bind close/minimize/maxmize/restore buttons like this 
      window.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, OnCloseWindow));
      window.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, OnMaximizeWindow, OnCanResizeWindow));
      window.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, OnMinimizeWindow, OnCanMinimizeWindow));
      window.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, OnRestoreWindow, OnCanResizeWindow));
                  
      window.ShowDialog();
   }

   public void Close_window(object viewmodel)
   {
       //Close window
       foreach (Window item in Application.Current.Windows)
       {
          if (item.Content == viewmodel) item.Close();
       }
    }
}

使用我的方法很简单。通常你想在它发生某些事情时关闭窗口。因此,当它这样做时,只需从相应的 ViewModel 调用Close_window方法——即显示在窗口中的 UserControl 的 DataContext 方法。看底部示例:

1.) 我们从一些 Viewmodel 打开 Window:

public class MyViewModel // ViewModel where you open window
{
   private readonly WindowService _windowservice // or inject/inherit from Base

   public MyViewModel()
   {
     _windowservice = new WindowService();
   }  

   private void Example_method()
   {
        //...Open window
        _windowservice.Show_window(new WindowViewModel(),100,100,"Test window");
   }
  
}

2.)我们的窗口已经打开,现在我们要关闭它:

 public class WindowViewModel // ViewModel which is your Window content!
 {
     private readonly WindowService _windowservice // or inject/inherit from Base

     public MyViewModel()
     {
       _windowservice = new WindowService();
     }  

     private void Example_method()
     {
          //Close window
          _windowservice.Close(this); //Pass a reference of viewmodel to method
     }
    
  }

这个解决方案远没有其他公认的答案那么优雅,但对我来说它有效。我在项目中广泛使用它,到目前为止它没有问题。但我敢肯定,有人会说“这违反了 MVVM 原则”。

于 2021-04-11T16:59:15.643 回答
-1

您只需使用以下代码即可关闭当前窗口:

Application.Current.Windows[0].Close();
于 2014-07-15T06:42:23.680 回答
-7

System.Environment.Exit(0); 在视图模型中会起作用。

于 2014-05-09T08:21:25.363 回答