tags:

views:

54

answers:

2

Two questions here.

My view has a "close" button that when clicked, the window should close. I handled this as follows: The button in my view binds to a command defined in the view's view model, which when triggered runs the following:

    private void Exit()
    {
      var regionManager = Container.Resolve<IRegionManager>();
      MyView existingView = regionManager.Regions["MyWindowRegion"].GetView("MyView") as MyView;

      if (existingView != null)
      {
        regionManager.Regions["MyWindowRegion"].Remove(existingView);
      }
    }

Is this ok? Does the view model now know too much about the view (such as its name and type)?

Similar to the first question, in my module toolbar, if I hit a "launch module" button it will create/display a view. I made it so that if the view is already visible, instead of creating it again, the view model will just bring the existing one into focus:

    private void LaunchMyView()
    {
      var regionManager = Container.Resolve<IRegionManager>();
      MyView existingView = regionManager.Regions["MyWindowRegion"].GetView("MyView") as MyView;

      if (existingView == null)
      {
        MyView view = Container.Resolve<MyView>();
        view.Title = "MyView Title";
        regionManager.Regions["MyWindowRegion"].Add(view, "MyView");
      }
      else
      {
        regionManager.Regions["MyWindowRegion"].Activate(existingView);
      }
    }

Same question. Does the view model know too much about the view?

Btw, I am using the WindowsRegionAdapter to handle new view creation.

Thanks.

A: 

If all you want to do is close the Window then use the IsCancel property for the Button in your XAML.

Here is an example:

<Button Content="Close"
        IsCancel="True"
        Width="70" 
        Height="23" />
Zamboni
+1  A: 

Strictly speaking the ViewModel doesn't know anything about the view in your code, but it does know about a RegionManager (well, grabs it from the Container), which is doing the work.

Personally, for this kind of thing, I prefer to use the mediator pattern to simply publish messages from the ViewModel, such as "OK, I'm done here". The region manager object would subscribe to these messages and handle the close as appropriate. In this way you have moved the code out of your ViewModel and hopefully you can feel better about the VM not being able to 'see' the View.

In Prism we use a class called EventAggregator to pub/sub classes of type CompositeWpfEvent<TPayload>

IanR