Close View from ViewModel

Topics: Prism v2 - WPF 3.5
Sep 13, 2009 at 9:22 AM

How do I close a View from its ViewModel?

I've a WPF window which has defined multiple Regions and being used as a Shell to host views for my application. I would like to have a View able to remove itself from the Region, or close it from a tabbed container. How can I accomplish this behavior from ViewModel.

Sep 14, 2009 at 6:57 AM


 At some point you must have used the RegionManager to register the view with a region (let's say the TabRegion). All you have to do is to remove the view from that region in order to close it.

Sep 14, 2009 at 7:17 AM

Yes, but how can I access RegionManager from ViewModel? Or where should I hook an event to be raised from ViewModel that could remove View from RegionManager?


Sep 14, 2009 at 10:18 AM
Edited Sep 14, 2009 at 10:19 AM

u could do the following



class ViewModel
     public event RequestClose;
     public ICommand CloseCommand { get; private set; } // Bind to some button?

     public ViewModel
        this.CloseCommand = new DelegateCommand<object>(() => RequestClose(this, null), () => RequestClose != null);

class ShellView
     IRegionManager regionManager;
     public ShellView(IRegionManager regionManager)
         this.regionManager = regionManager;

     public void Initialize()
           ViewModel vm  = new ViewModel();
           vm.RequestClose += () => regionManager.Regions["MyRegion"].Remove(vm);