【问题标题】:wpf prism (CAL) - Closing Window in Popup Region when the ViewModel knows nothing of the Viewwpf prism (CAL) - 当 ViewModel 对视图一无所知时关闭弹出区域中的窗口
【发布时间】:2010-03-24 13:15:14
【问题描述】:

我们在 shell 的 Window 标签中有一个 Region,向这个区域添加东西会弹出另一个 Window。

<Window x:Class="GTS.GRS.N3.Shell.Shell1"
 --removed namespace references for clarity
    cal:RegionManager.RegionName="{x:Static Constants:RegionNames.WindowRegion}">  

我们将 ViewModels 添加到区域管理器,然后通过数据上下文附加视图,以便 ViewModel 对视图一无所知,即

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <DataTemplate DataType="{x:Type Model:CommunicationViewModel}">
       <v:CommunicationView />
    </DataTemplate>
</ResourceDictionary>

我的问题是如何关闭弹出窗口,我尝试从 RegionManager 中删除 ViewModel - 但是这个例外......视图是一个用户控件,但我需要关闭它的所有者,这是一个由打开的新窗口该区域。我真的不想通过 ViewModel 的 DataContext 破解它。

有人可以帮忙吗?

【问题讨论】:

  • 你有一个窗口的 RegionAdapter 吗?一个 Window 是一个 ContentControl (所以它应该可以工作),但我从来没有听说过有人这样做,我绝对不会期望它在向该区域添加某些内容时弹出窗口。你能分享一下这个例外吗?

标签: wpf mvvm prism


【解决方案1】:

安迪,

我自己花了很长时间才弄清楚这一点。

最简洁的方法是使用 DelegateCommand(或 RelayCommand)并在代码中添加一个事件处理程序,使用 window.Show() 创建窗口。

// Define the View
Shell window = Container.Resolve<Shell>();

// Define the ViewModel
ShellViewModel windowVM = Container.Resolve<ShellViewModel>();

// When the ViewModel asks to be closed, close the View.
EventHandler handler = null;
handler = (sender, e) =>
{
    windowVM.RequestClose -= handler;
    window.Close();
};
windowVM.RequestClose += handler;

// Set the ViewModel as the DataContext of the View
window.DataContext = windowVM;

// Display the View
window.Show();

然后我使用复合事件通知窗口的 ViewModel(不是 UserControl 的)它有关闭请求。为复合事件分配的订阅处理程序然后调用this.OnRequestClose()

在 ViewModel 的构造函数中:

//subscribe to composite events
_eventAggregator.GetEvent<WindowCloseEvent>().Subscribe(WindowClose);

在 ViewModel 的主体中:

/// <summary>
/// Private Event handler for WindowCloseEvent.
/// </summary>
private void WindowClose(bool value)
{
    // Close the View
    this.OnRequestClose();
}

有关更多信息,请参阅 Josh Smith 在 MSDN 上关于将 M-V-VM 模式与 WPF 结合使用的优秀文章http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

【讨论】:

  • 感谢您的回复。在我的场景中,我使用基于视图的导航,其中视图被添加到一个区域。我的目标是从 ViewModel 中关闭视图(即从区域中删除它),而不将视图类型或名称包含在模型中。这样做的有效方法是什么?
【解决方案2】:

_regionManager.Regions[RegionNames.PopupRegion].Deactivate(_regionManager.Regions[RegionNames.PopupRegion].ActiveViews.FirstOrDefault());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多