代码之家  ›  专栏  ›  技术社区  ›  Andy Clarke

wpf prism(CAL)-当ViewModel对视图一无所知时,在弹出区域关闭窗口

  •  0
  • Andy Clarke  · 技术社区  · 16 年前

    在shell的Window标签中有一个区域,向这个区域添加内容会弹出另一个窗口。

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

    我们将ViewModels添加到Region Manager中,然后通过数据上下文附加视图,这样ViewModel对视图一无所知,即。

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

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

    有人能帮忙吗?

    2 回复  |  直到 16 年前
        1
  •  3
  •   Shimmy Weitzhandler 500 - Internal Server Error    15 年前

    安迪,

    我花了很长时间才弄明白这一点。

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

    // 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()

    //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();
    }
    

    http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

        2
  •  0
  •   Gerald G.    12 年前

    _区域经理。区域[地区名称.PopupRegion].停用(_区域经理。区域[地区名称.PopupRegion].ActiveViews.FirstOrDefault());