Practical .NET

Communicating Between Views in WPF and Prism

As you navigate between one View and another using Prism's Navigation API, you'll need to pass data between your Views. Here are the tools you need.

I know that I've been going on for two months now about WPF with Prism and Unity -- but it's very cool technology and, I think, the way that large desktop applications should be built (I'm sure a whole bunch of readers just said "But why build desktop applications?"). But since I don't want to fatigue you, this is my last WPF + Prism + Unity column (at least for a while), I promise.

In my last column I introduced Prism's Navigation API, which lets you manage which View is displayed in a Region using only the RequestNavigate method. I'm willing to bet you'll want to pass data between one View (a list of customers, for instance) and the View to which the user has navigated (the CustomerID for the currently selected customer in the list).

To pass data to a View, you can add name/value pairs to the RequestNavigate method. First, you need to create a UriQuery object. Once you've done that, you can add named values to it. This example checks to see if a list of Customers has any items in it, and uses that information to set the value of a CustomersFetched name added to the query:

Microsoft.Practices.Prism.UriQuery qry = new Microsoft.Practices.Prism.UriQuery();
if (clvm.Customers.Count > 0) 
{
 qry.Add("CustomersFetched", "true");
}
else
{
 qry.Add("CustomersFetched", "false");                
}

That query can be added to the name of the View used to create the Uri object that's passed to the RequestNavigate method. This example adds the UriQuery I just created to the View name CustListViewShort, before passing the resulting Uri object to the RequestNavigate method:

Uri vu = new  Uri("CustListViewShort" + qry.ToString(), UriKind.Relative);
rgn.RequestNavigate(vu,GetCustomers);
Retrieving Data
To gain access to the data passed in a UriQuery, the ViewModel for the View that's the target of the RequestNavigate method must implement the INavigationAware interface:
public class CustListVM :  Microsoft.Practices.Prism.Regions.INavigationAware
{

This interface adds three new methods to your ViewModel: IsNavigationTarget, OnNavigatedFrom, and OnNavigatedTo. All three methods are passed a NavigationContext object (called navigationContext by default), which gives you access to information about the current navigation. The OnNavigatedFrom method is called in the ViewModel that's being navigated away from (i.e., the ViewModel whose code called the RequestNavigate method).

The OnNavigatedTo and IsNavigationTarget methods are called in the ViewModel of the View that was the target of the RequestNavigate method (i.e., the View about to be displayed).

In the OnNavigatedFrom method, you can add parameters to the Navigation query. If you'd prefer not to tack query parameters onto the end of the ViewName when creating your Uri, you can add the parameters in the OnNavigatedFrom method. This is a useful place to add parameters that you want added to every navigation request. This example adds the name of the class for the page issuing the navigation request:

public void OnNavigatedFrom(Microsoft.Practices.Prism.
       Regions.NavigationContext navigationContext)
{
  navigationContext.Parameters.Add("PageFrom", this.ToString();
}

In the OnNavigatedTo method, you can access parameters added in the RequestNavigate or OnNavigatedFrom methods, through the NavigationContext object passed to OnNavigatedTo method. This example checks for the CustomersFetched parameter, and if it's found, calls a method to populate the list of customers in the new View:

public void OnNavigatedTo(Microsoft.Practices.Prism.
   Regions.NavigationContext navigationContext)
{
  if (navigationContext.Parameters["CustomersFetched"] == "true")
  {
     this.GetCustomers(this);
  }
}

It's a simple mechanism, but does have the benefit of being relatively easy to understand; and it lets one View talk to the next View, which is all you really need.

Lagniappe
Just for completeness' sake: The IsNavigationTarget allows you to check to see if your ViewModel should accept the navigation request. If you don't want your View displayed, return false from the IsNavigationTarget method; otherwise return true. This example checks to make sure that the CustomersFetched parameter is present, and if it is, that it's set to one of the two acceptable values:
public bool IsNavigationTarget(Microsoft.Practices.Prism.Regions.
  NavigationContext navigationContext)
{
  if (navigationContext.Parameters.Contains(new
    KeyValuePair<string,string>("CustomersFetched","true")) == true 
    ||
     navigationContext.Parameters.Contains(new
   KeyValuePair<string,string>("CustomersFetched","false")) == true)
  {
    return false;
  }
  else
  {
    return true;
  }
}
And now, I promise that I'm done with WPF -- at least, for a while (this is very cool technology). Next month, back to the Web.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube