打开WPF窗口MVVM并关闭它



可能的重复:
WPF MVVM新手-ViewModel应该如何关闭表单?

我在stackoverflow周围搜索过,我认为给出的答案不适用于我,或者我不知道如何应用它们。

我有一个标准的MVVM WPF应用程序。MVVM部分由RelayCommand类、ViewModelBase类和扩展ViewModelBase的WorkspaceViewModel类组成。

我有两个窗口,MainWindow和CustomMessageBox窗口(它实际上为用户提供了一个问题和两个答案)。我在主窗口中使用此代码打开CustomMessageBox(第二个窗口):

public ICommand BrowseFileFolderCommand
{
get
{
if (_browseFileFolderCommand == null)
{
_browseFileFolderCommand = new RelayCommand(o =>
{
var messageViewModel = new MessageBoxViewModel("Add a Folder or File", "What do you wish to add, folder or file?", "Folder", "File");
var choice = new CustomMessageBox()
{
DataContext = messageViewModel
};
choice.ShowDialog();
if (messageViewModel.CustomMessageBoxDialogResult == DialogResult.Yes)
{
switch (messageViewModel.ChosenEntity)
{
case SelectedAnswer.Answer1:
// Get folder shizz
break;
case SelectedAnswer.Answer2:
// Get file shizz
break;
default:
break;
}
}
}, null);
}
return _browseFileFolderCommand;
}
}

一旦启动了CustomMessageBox,我就无法使用CloseCommand关闭它。当我尝试调试CustomMessageBox的加载时,似乎所有的ICommands都在我按下任何东西之前被触发了?

WorkspaceViewModel具有CloseCommand:

#region CloseCommand
/// <summary>
/// Returns the command that, when invoked, attempts
/// to remove this workspace from the user interface.
/// </summary>
public ICommand CloseCommand
{
get
{
if (_closeCommand == null)
_closeCommand = new RelayCommand(param => this.OnRequestClose());
return _closeCommand;
}
}
#endregion // CloseCommand
#region RequestClose [event]
/// <summary>
/// Raised when this workspace should be removed from the UI.
/// </summary>
public event EventHandler RequestClose;
void OnRequestClose()
{
EventHandler handler = this.RequestClose;
if (handler != null)
handler(this, EventArgs.Empty);
}
#endregion // RequestClose [event]

有人有什么想法吗?我遗漏了什么关键的东西吗?

谢谢,

当我需要完成这项工作时,我从Command.Execute逻辑中调用以下代码行:

App.Current.Windows.Cast<Window>().Where(win => win is CustomMessageBox).FirstOrDefault().Close();

我希望这能有所帮助。

我实际上没有将任何方法附加到事件处理程序,所以当调用事件处理程序时,由于代码走到了死胡同,什么都没做,所以我更改了代码,并将Window的Close方法附加到ViewModel的事件处理程序:

messageViewModel.RequestClose += (s, e) => choice.Close();

这是完整的代码:

public ICommand BrowseFileFolderCommand
{
get
{
if (_browseFileFolderCommand == null)
{
_browseFileFolderCommand = new RelayCommand(() =>
{
var messageViewModel = new MessageBoxViewModel("Add a Folder or File", "What do you wish to add, folder or file?", "Folder", "File");
var choice = new CustomMessageBox()
{
DataContext = messageViewModel
};
// Added this line
messageViewModel.RequestClose += (s, e) => choice.Close();
choice.ShowDialog();
if (messageViewModel.CustomMessageBoxDialogResult == DialogResult.Yes)
{
switch (messageViewModel.ChosenEntity)
{
case SelectedAnswer.Answer1:
// Get folder shizz
break;
case SelectedAnswer.Answer2:
// Get file shizz
break;
default:
break;
}
}
}, null);
}
return _browseFileFolderCommand;
}
}

感谢大家帮助我得到答案,这只是为了澄清我的问题。

谢谢。

最新更新