PDFx – Property Dependency Framework – Part VI, External Property Dependencies

The PDFx is a lightweight open source .NET library that allows developers to describe dependencies between Properties in declarative C# code. Once relationships are registered, the framework monitors property changes and ensures that the INotifyPropertyChanged.PropertyChanged event is fired for all directly and indirectly dependent properties in a very efficient way. The library is available for WPF, Silverlight, WinRT (Windows Store) and Windows Phone.

I’ve developed the PDFx as an InterKnowlogy RECESS project and published the source code and examples on codeplex.

In a series of blog posts I am going to cover the library’s most important features:

External Property Dependencies

Declarative Usage

The declarative PDFx API allows you to register a dependency on a property that resides in any INotifyPropertyChanged-instance different from the owner of the dependent Property:

class SourceClass : INotifyPropertyChanged
{
	private AnyType _sourceProperty;
	public AnyType SourceProperty
	{
		get { return _sourceProperty; }
		set
		{
			_sourceProperty = value;
			OnPropertyChanged("SourceProperty");
		}
	}
}

class DestinationClass : BindableExt
{
	SourceClass Source { get; set; }

	public AnyOtherType TargetProperty
	{
		get
		{
			Property(() => TargetProperty)
				.Depends(p => p.On(Source, k => k.SourceProperty));

			//Source.SourceProperty has changed. Do Something with it and return.
		}
	}
}

Overloads of the methods On and AndOn both allow you to pass in an INotifyPropertyChanged instance as the first parameter and point to any property of that instance in the Lambda Expression you pass in as the second parameter.

Example

The source code of this example can be found in ViewModel ExternalDependencyVM which is part of the WPFSample’s source code.

Let’s assume we are required to implement the following graph:

ExternalPropertyDependencies.png
Green circles stand for Input Properties while purple circles indicate calculated properties. The arrows show the underlying math operations as well as the property dependencies.

Using the PDFx, we can easily represent the depicted graph in C#:

public class DestinationVM : BindableExt
{
	public DestinationVM()
	{
		ExternalSource1 = new ExternalSource1();
		ExternalSource2 = new ExternalSource2();
	}

	public ExternalSource1 ExternalSource1 { get; private set; }
	public ExternalSource2 ExternalSource2 { get; private set; }

	public int A1
	{
		get
		{
			Property(() => A1)
				.Depends(p => p.On(() => B1)
						.AndOn(ExternalSource1, k => k.A1)
						.AndOn(ExternalSource2, k => k.A1));

			return B1 + ExternalSource1.A1 - ExternalSource2.A1;
		}
	}

	private int _b1;
	public int B1
	{
		get { return _b1; }
		set { _b1 = value; NotifyPropertyChanged(() => B1); }
	}
}

public class ExternalSource1 : BindableExt
{
	public int A1
	{
		get
		{
			Property(() => A1)
				.Depends(p => p.On(() => B1));

			return 3 * B1;
		}
	}

	private int _b1;
	public int B1
	{
		get { return _b1; }
		set { _b1 = value; NotifyPropertyChanged(() => B1); }
	}
}

public class ExternalSource2 : BindableExt
{
	private int _a1;
	public int A1
	{
		get { return _a1; }
		set { _a1 = value; NotifyPropertyChanged(() => A1); }
	}
}

PDFx – Property Dependency Framework – Part V, Simple Property Dependencies

The PDFx is a lightweight open source .NET library that allows developers to describe dependencies between Properties in declarative C# code. Once relationships are registered, the framework monitors property changes and ensures that the INotifyPropertyChanged.PropertyChanged event is fired for all directly and indirectly dependent properties in a very efficient way. The library is available for WPF, Silverlight, WinRT (Windows Store) and Windows Phone.

I’ve developed the PDFx as an InterKnowlogy RECESS project and published the source code and examples on codeplex.

In a series of blog posts I am going to cover the library’s most important features:

Simple Property Dependencies

After you’ve followed the instructions from Getting Started, you are ready to use the PDFx.

Declarative Usage

The declarative PDFx API allows you to register a property dependency from within a property getter’s implementation following this pattern:

class MyClass : BindableExt
{

    AnyType MyTargetProperty
    {
       get 
       {
             Property(() => MyTargetProperty)
                 .Depends(p => p.On(() => FirstSourceProperty)
                                  .AndOn(() => SecondSourceProperty)
                                  .AndOn(() => LastSourceProperty));

            //Do something with the values of those 3 Properties and return a result     
        }       
    }

    AnyType FirstSourceProperty { get { } set { } }
    AnyType SecondSourceProperty { get { } set { } }
    AnyType LastSourceProperty { get { } set { } }

}

The call to method Property expects a lambda expression which points to the Property in which your code resides. The PDFx will use this expression to resolve the property’s name.
The returned object of method Property allows you to call the method Depends which expects a delegate that accepts a parameter of the fluent interface type IPropertyDependencyExt (or IPropertyDependency in the case of the PCL’s Bindable class).
This parameter allows you to specify source properties your current target property depends on by calling the On and AndOn methods. Both methods always return the very same instance of the interface type IPropertyDependencyExt, thereby allowing you to register the entire property registration in a single execution.

Example

The source code of this example can be found in ViewModel SimplePropertyDependencyVM which is part of the WPFSample’s source code.

Let’s assume we are required to implement the following graph:

SimplePropertyDependenciesPicture.png
Green circles stand for Input Properties while purple circles indicate calculated properties. The arrows show the underlying math operations as well as the property dependencies.

Using the PDFx’s Simple Property Dependencies feature, we can easily represent the depicted graph in a ViewModel similar to this:

class SimplePropertyDependencyVM : BindableExt
{
	public int A1
	{
		get
		{
			Property(() => A1)
				.Depends(p => p.On(() => B1)
						.AndOn(() => B2));

			return B1 + B2;
		}
	}

	public int B1
	{
		get
		{
			Property(() => B1)
				.Depends(p => p.On(() => C1)
						.AndOn(() => C2));

			return 2 * C1 - C2;
		}
	}

	public int B2
	{
		get
		{
			Property(() => B2)
				.Depends(p => p.On(() => C2)
						.AndOn(() => C3));

			return -C2 + C3;
		}
	}

	public int C1
	{
		get
		{
			Property(() => C1)
				.Depends(p => p.On(() => D1)
						.AndOn(() => D2));

			return D1 + D2;
		}
	}

	public int C2
	{
		get
		{
			Property(() => C2)
				.Depends(p => p.On(() => D3));

			return 3 * D3;
		}
	}

	public int C3
	{
		get
		{
			Property(() => C3)
				.Depends(p => p.On(() => D4)
						.AndOn(() => D5));

			return D4 + D5;
		}
	}

	private int _d1;
	public int D1
	{
		get { return _d1; }
		set
		{
			_d1 = value; 
			NotifyPropertyChanged(() => D1);
		}
	}

	private int _d2;
	public int D2
	{
		get { return _d2; }
		set
		{
			_d2 = value;
			NotifyPropertyChanged(() => D2);
		}
	}

	private int _d3;
	public int D3
	{
		get { return _d3; }
		set
		{
			_d3 = value;
			NotifyPropertyChanged(() => D3);
		}
	}

	private int _d4;
	public int D4
	{
		get { return _d4; }
		set
		{
			_d4 = value;
			NotifyPropertyChanged(() => D4);
		}
	}

	private int _d5;
	public int D5
	{
		get { return _d5; }
		set
		{
			_d5 = value;
			NotifyPropertyChanged(() => D5);
		}
	}
}

PDFx – Property Dependency Framework – Part IV, Using PDFx with an existing 3rd party framework

The PDFx is a lightweight open source .NET library that allows developers to describe dependencies between Properties in declarative C# code. Once relationships are registered, the framework monitors property changes and ensures that the INotifyPropertyChanged.PropertyChanged event is fired for all directly and indirectly dependent properties in a very efficient way. The library is available for WPF, Silverlight, WinRT (Windows Store) and Windows Phone.

I’ve developed the PDFx as an InterKnowlogy RECESS project and published the source code and examples on codeplex.

In a series of blog posts I am going to cover the library’s most important features:

Using PDFx with MVVM Light

Full Disclosure: The implementation presented in this post is experiential. While it passes the PDFx’s Unit Tests successfully, it has not undergone several months of stress tests in IK’s production environments (in contrast to the PDFx itself) because we’re using our own in house ViewModel base class and are consequently able to derive from BindableExt.

In Getting Started you’ve learned what steps you have to take in order to use the PDFx in your own project. As it was explained, every class that wants to leverage PDFx’s features needs to ultimately derive from PDFx’s Bindable or BindableExt because all the functionality is exposed through protected methods.

In certain scenarios, however, the ViewModel Base class that you’re using throughout the project might live in a 3rd party assembly and you might consequently not have the option to modify its source code to include the PDFx.

In order to still support those scenarios, I’ve extended the PDFx’s base classes to expose their functionality not only through protected methods but also through explicitly implemented interfaces. This allows you to use the PDFx in your project by implementing an intermediate man-in-the-middle ViewModel class that bridges the gap between your ViewModel base class and the PDFx. The following steps are necessary to implement such an intermediate ViewModel (You can skip the following steps and immediately head to the next section of this post if you would like to reuse my implementation):

Let’s assume every ViewModel in your project derives from ViewModelBase that is exposed by a 3rd party library.

  1. Create a new class MyViewModel and derive it from ViewModelBase.
  2. Change every reference in your project from ViewModelBase to MyViewModel.
  3. Create a nested BindableExt or Bindable instance inside of MyViewModel (See Library Versions to find out which one suits your needs best)
    1. If you use Bindable, create delegating methods within MyViewModel for every method the Bindable instance exposes through its explicitly implemented interface IBindableAccessToProtectedFunctionality. Omit the “Tunnelled” prefixes.
    2. If you use BindableExt, create delegating methods within MyViewModel for every method the BindableExt instance exposes through its explicitly implemented interface IBindableExtAccessToProtectedFunctionality. Omit the “Tunnelled” prefixes.
  4. Intercept every method call to ViewModelBase which ultimately results in raising the PropertyChange event and forward it instead to the Bindable instance’s TunnelledNotifyPropertyChanged method.
  5. Forward every PropertyChanged event that the Bindable instance raises to ViewModelBase’s PropertyChanged event.
  6. Implement the IDependencyFrameworkNotifyPropertyChangedInTransaction interface in MyViewModel
    1. Forward the interface’s FirePropertyChanged method to the Bindable Instance’s, which also implements the IDependencyFrameworkNotifyPropertyChangedInTransaction interface.
    2. Forward every PropertyChangedInTransaction event that is raised by the Bindable Instance to the PropertyChangedInTransaction event MyViewModel now exposes.

I’ve implemented such an intermediate ViewModel class for MVVMLight. You can find the full example here. In this scenario I’ve chosen to use PDFx’s BindableExt version (See Library Versions for more information).

How to use PDFx with a framework different from MVVM Light

In case you don’t use MVVM Light, you can still use the intermediate class i’ve implemented for MVVM Light as a starting point and follow a few simple steps to make it work with your framework:

  1. Get the intermediate class’s source code from here.
  2. Change the intermediate class’s base class from MVVMLight’s ViewModelBase to the ViewModel base class that comes with your framework.
  3. Change the intermediate class’s MVVM Light Specific region
    1. Override whatever method your base class uses to ultimately raise the PropertyChanged event and forward it to the PDFx’s TunnelledNotifyPropertyChanged method.
    2. Change the FirePropertyChanged method’s implementation to call your base class’s method which raises the PropertyChanged event. This should be the very same method you overwrote in the previous step.

If you want to make sure that you followed the steps correctly and that the PDFx is ready to use, I recommend running the MVVMLightExtension’s Unit Tests against your new intermediate ViewModel.

PDFx – Property Dependency Framework – Part III, Getting started

The PDFx is a lightweight open source .NET library that allows developers to describe dependencies between Properties in declarative C# code. Once relationships are registered, the framework monitors property changes and ensures that the INotifyPropertyChanged.PropertyChanged event is fired for all directly and indirectly dependent properties in a very efficient way. The library is available for WPF, Silverlight, WinRT (Windows Store) and Windows Phone.

I’ve developed the PDFx as an InterKnowlogy RECESS project and published the source code and examples on codeplex.

In a series of blog posts I am going to cover the library’s most important features:

Using PDFx in your Project

Adding a reference to the PDFx

Before using the PDFx, you have to decide whether you would like to go with the platform independent Portable Class Library or one of the feature richer platform specific libraries. Please check out Library Versions to learn more about the different versions.

If you decide to go forward with the Portable Class library, all you need to do is add a project reference to PropertyDependencyFramework.dll.

If you decide to go forward with a platform specific library (recommended), you need to add a project reference to PropertyDependencyFramework.dll and a platform specific binary.

Platform .NET 4.5 Portable Class Library
Path bin\Release\PCL\PropertyDependencyFramework.dll
WinRT WP8
bin\Release\WindowsStore\PropertyDependencyFramework.dll &
bin\Release\WindowsStore\PropertyDependencyFramework_WindowsStore.dll
bin\Release\WP8\PropertyDependencyFramework.dll &
bin\Release\WP8\PropertyDependencyFramework_WP8.dll
WPF SL5
bin\Release\WPF\PropertyDependencyFramework.dll & bin\Release\WPF\PropertyDependencyFramework_WPF.dll bin\Release\SL5\PropertyDependencyFramework.dll &
bin\Release\SL5\PropertyDependencyFramework_Silverlight.dll

Deriving from Bindable

The PDFx’s features are all exposed through protected methods which live in the PCL’s Bindable-class as well as in the platform specific BindableExt-classes.
Every class, in which you would like to use the PDF’x functionality consequently needs to eventually derive from Bindable or BindableExt which both live in the PropertyDependencyFramework-Namespace.

In case you’re already using a development framework (such as MVVMLight) and cannot or don’t want to change your ViewModel’s base class, please refer to Using PDFx with an existing 3rd party framework to learn how you can merge the PDFx into those scenarios.

PDFx – Property Dependency Framework – Part II, Library Versions

The PDFx is a lightweight open source .NET library that allows developers to describe dependencies between Properties in declarative C# code. Once relationships are registered, the framework monitors property changes and ensures that the INotifyPropertyChanged.PropertyChanged event is fired for all directly and indirectly dependent properties in a very efficient way. The library is available for WPF, Silverlight, WinRT (Windows Store) and Windows Phone.

I’ve developed the PDFx as an InterKnowlogy RECESS project and published the source code and examples on codeplex.

In a series of blog posts I am going to cover the library’s most important features:

Library Versions

The core of the framework lives in the PropertyDependencyFramework-assembly which is a Portable Class Library. Some optional PDFx features require platform specific functionality that does not come with the .NET Portable Subset. Thus, there exist platform specific libraries for WPF, Silverlight 5, WP8, Windows Store which extend the basic PropertyDependencyFramework-assembly.

If there exists a specific library for your target platform, I strongly recommend using it. If not, you can always fall back on the PCL.

Feature .NET 4.5 Portable Class Library WinRT WP8 WPF SL5
Simple Property Dependencies x x x x x
Property Dependencies to external objects x x x x x
Property Dependencies to ObservableCollections x x x x x
Callbacks x x x x x
Property Dependencies to hot swappable external objects   x x x x
Property Dependencies to hot swappable ObservableCollections   x x x x
Deferred Callbacks   x x x x
Sanity Checks       x x

PDFx – Property Dependency Framework – Part I, Introduction

The PDFx is a lightweight open source .NET library that allows developers to describe dependencies between Properties in declarative C# code. Once relationships are registered, the framework monitors property changes and ensures that the INotifyPropertyChanged.PropertyChanged event is fired for all directly and indirectly dependent properties in a very efficient way. The library is available for WPF, Silverlight, WinRT (Windows Store) and Windows Phone.

I’ve developed the PDFx as an InterKnowlogy RECESS project and published the source code and examples on codeplex.

In a series of blog posts I am going to cover the library’s most important features:

Introduction

The Property Dependency Framework (PDFx) is a lightweight library that allows you to capture the inherent relationship among the properties of your classes in a declarative manner. It is common in applications to have properties whose values depend upon the values of other properties. These properties need to be reevaluated when a change occurs in the properties on which they depend. For example, if “A” depends on “B” and “C”, we need to reevaluate the value of A whenever either B or C changes. Furthermore, B and C may not even be direct properties of the same class as that in which A exists. Instead, they may be properties of another class, or even properties of the items within a collection.

In large applications, complex chains of such dependencies can exist. Although C# gives us the INotifyPropertyChanged construct to send out a change notification (typically to UI elements), no framework to our knowledge has allowed the network of dependencies to be specified in a straightforward manner, with the proper change notifications issued automatically. The PDFx framework allows the dependencies of properties to be specified declaratively, building from them an internal network of dependencies for you. Changes to any property in the network are then propagated automatically and efficiently.

The PDFx framework establishes a simple pattern for capturing the relationships of data in applications, and removes tremendous amounts of “plumbing”. It also helps clarify and enhance the role of the View Model within MVVM, reducing the scattering of business logic throughout value converters. Once you’ve made use of PDFx, you will likely wonder how the gap it fills has gone unaddressed for so long.

Example

Since pictures tell better stories than words, I would like to demonstrate the benefits of this workhorse with a small example:

PDFX.png

The depicted algebra hierarchy represents a C# class. Green circles stand for Input Properties while purple circles indicate calculated properties. The arrows show the underlying math operations as well as the property dependencies.
As the developer of such a scenario, you’re responsible to ensure that all directly and indirectly dependent properties get reevaluated when an input property changes. Furthermore, for efficiency reasons, you also want to ensure that all unrelated properties do not get reevaluated.

If, for example, Property D1 changes, it is necessary to reevaluate C1, B1 and A1.
However, a change of D3 requires a reevaluation of only C2, B1, B2 and A1.

Using the PDFx, you don’t have to manually hardcode those relationships anymore but can rather rely on the library taking care of this job for you.
All you have to do is register the relationships in human readable code within the implementation of a property:

//....
public int A1
{
	get
	{
		Property(() => A1)
			.Depends(p => p.On(() => B1)
			               .AndOn(() => B2));
		
		return B1 + B2;
	}
}

public int B1
{
	get
	{
		Property(() => B1)
			.Depends(p => p.On(() => C1)
			               .AndOn(() => C2));
		
		return 2*C1 - C2;
	}
}

public int B2
{
	get
	{
		Property(() => B2)
			.Depends(p => p.On(() => C2)
			               .AndOn(() => C3));
		
		return -C2 + C3;
	}
}

public int C1
{
	get
	{
		Property(() => C1)
			.Depends(p => p.On(() => D1)
			               .AndOn(() => D2));

		return D1 + D2;
	}
}

public int C2
{
	get
	{
		Property(() => C2)
			.Depends(p => p.On(() => D3));

		return 3*D3;
	}
}

public int C3
{
	get
	{
		Property(() => C3)
			.Depends(p => p.On(() => D4)
			               .AndOn(() => D5));
		
		return D4 + D5;
	}
}
//....

Advanced Features

  • Dependencies on properties of external objects
  • Dependencies on ObservableCollections
  • Property Value Caching
  • (Deferred) Callbacks for Property Changes

Main Benefits

  • The dependency registration resides within the Property Getter implementation. This way you’re likely to notice immediately that an update of the registration is necessary when you change a property’s implementation.
  • The PDFx fires the PropertyChanged event only for Properties that are directly or indirectly dependent on the changed source property, thereby guaranteeing a high level of efficiency.
  • Properties whose data relies completely on the value of other properties do not need to encapsulate backing fields. They can be implemented solely in the Property Getter, thereby ensuring full integrity.

Nokia – San Diego Windows Phone 8 Hackathon – May 2013

The San Diego Windows Phone 8 Hackathon held at Nokia on May 11th 2013 was a huge success! I want to express my sincere appreciation and respect to all who participated. We had 33 Windows Phone 8 Apps submitted after a mere 4 hours of development time. That’s quite an impressive feat, especially considering the quality of the apps that were presented! I hope everyone that participated will put the finishing touches on their apps and submit them to the Windows Phone Store. (And let me know!)

I took a new approach to presenting code topics at this event and I am quite pleased how it turned out. We held 3 sessions each 1 hour long. Between each session was 1 hour for hands on lab. In the past I’ve shown different codebases for my presentation vs. any hands on labs. At this event I decided to try to use the same codebase for both. This meant I could show off a working version of the hands on labs before attendees would start them. This gave the attendees greater understanding about what they were about to do and how the code topics work in an app setting instead of some simplified, non-best practices sample. This worked tremendously well. I received many comments from attendees about how much they loved seeing the code first then writing the code themselves, and how that was much more effective than seeing two different samples. The apps shown off during the hackathon were evidence to me that my approach was effective and good.

This event was not my first; however it was my first with 111 attendees! It was also my first as a Nokia Developer Champion. I had a blast and the atmosphere and enthusiasm of attendees told me that everyone else did too. I look forward to the many follow up sessions we discussed during the event and other events coming up in the future!

Link to event materials: NokiaWP8May2013

WinRT Framework: Application State

From the previous blog entry, on our diary application, we used the framework to help us navigate from the MainPage to the Diary Page and vice versa.
On the Diary Page, we will notice that if we write some text on the textbox, when we navigate away from that page and go back to the diary page, the text is not persisted. This means that the text is not stored. So navigating away from the page, we lose that text.

How do we fix this? Simple! The framework has its way! So, let’s get to coding mode.

1) Let’s edit the DiaryPageVM.cs and add a text property to bind to our textbox.
We also need a Bindable class (part of the framework) to have a way for us not be notified when the property is updated.
In the Bindable class, the NotifyPropertyChanged method fires the INotifyPropertyChanged.PropertyChanged event for the Property that you pass in.
Luckily, the framework already has a class we can inherit that takes care of this; instead of us making another helper class.

  public class DiaryVM : Bindable, IRequireNavigationService
    {
        public INavigationService NavigationService { set; get; }

        private string _diaryText;
        public string DiaryText
        {
            get { return _diaryText; }
            set
            {
                _diaryText = value;
                NotifyPropertyChanged(() => DiaryText);
            }
        }
    }

2) Now that we have a text property to bind to the textbox, we need the framework to persist the state of our application.
On the same page (DiaryPageVM.cs) we need an interface — ISupportTransientState

public class DiaryVM : Bindable, IRequireNavigationService, ISupportTransientState
  • This interface tells the framework that our ViewModel has a transient state.
  • The framework then is responsible for persisting and restoring the state.

3) Add a TransientState class that will have the properties that we need its state to be persisted — Text!

[DataContract]
public class TransientState
        {
            [DataMember]
            public string Text { get; set; }
        }
  • The DataContract and DataMember are both used for serialization. That means, the data is being stored and its value can be access in the same or different computer environment.

4) Implement the methods of the ISupportTransientState.
4a) GetTransientStateTypes() that returns all the TransientState that we need.

public IEnumerable GetTransientStateTypes()
        {
            yield return typeof(TransientState);
        }

4b) GetTransientState() that sets the value of the TransientState’s Text property to the DiaryText and creates an instance of the TransientState class.

public object GetTransientState()
        {
            return new TransientState { Text = DiaryText };
        }

4c) UpdateTransientState() that updates the value of the Text property when DiaryText gets updated.

public void UpdateTransientState(object untypedState)
        {
            TransientState state = (TransientState)untypedState;
            DiaryText = state.Text;
        }

5) Bind the DiaryText to the textbox in DiaryPage.xaml

        <TextBox Grid.Row="1"
                 HorizontalAlignment="Stretch"
                 VerticalAlignment="Stretch" Margin="100"
                 AcceptsReturn="True"
                 Text="{Binding DiaryText, Mode=TwoWay}"/>

And we are done! Now let’s run the program and make sure it works.
THINGS TO REMEMBER:

  • When we navigate to the DiaryPage and put some text on the textbox, and we navigate away from that page, the text gets persisted and clicking the ‘ForwardButton’ restores the state of the text.
  • Now the question is why not click the Go to Diary button (center) of the MainPage? On my previous blog entry about Navigation, I talked about when we click the Go to Diary button, we are creating a new instance of the DiaryPage. When we click that instead of the forward button, the text will not be there.
  • If we try to use the navigation arrows at the top of our application, we are keeping the same instance of the DiaryPage, which means we will see that the text is persisted

For reference, Here is a link to the solution

WinRT Framework: Navigation

On the WinRT Framework: Getting Started blog, we got everyone setup on referencing the Framework to our project.
Now we are ready to move on to Navigation.

Overview: For this example, we will make a Diary App that has a Main Page and Diary Page.
The Navigation between the Main page and Diary page will be a “Go Forward” and “Back” button.

1) Let us first create DiaryPageVM.cs (class) and a DiaryPage.xaml (page)

2) On MainPageVM.cs, we need a DelegateCommand to navigate to the diary page.

  • DelegateCommand works like a ‘Click’ property of a button, but unlike ‘Click’, DelegateCommand is used in the ViewModel and not on the code-behind.
  • This points out the idea of MVVM pattern that the view is decoupled from the viewmodel.
  • The implementation of IRequireNavigationService tells the framework that our ViewModel would like to get access to the Framework’s NavigationService in order to be able to navigate to other pages
  • This interface has a NavigationService property that has a Navigate method that we can use to tell framework which view model we want to navigate to.
  • In this case, we want to navigate to DiaryPageVM, so we can simply say NavigationService.Navigate<DiaryPageVM>();
public class MainPageVM : IRequireNavigationService
	{
		public DelegateCommand NavigateToDiaryCommand
		{
			get
			{
				return new DelegateCommand(() => NavigationService.Navigate());
			}
		}

		public INavigationService NavigationService { get; set; }
	}

3) On MainPage.xaml, we add the buttons to navigate to the Diary page
One button (in the middle) to instantiate a new instance of a diary page to navigate to.
The other button (at the top-left) to navigate to the same instance of the diary page that was already created.

 <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <Button HorizontalAlignment="Left"
                Command="{Binding NavigationService.GoForwardCommand}"
                Style="{StaticResource BackButtonStyle}">
            <Button.RenderTransform>
                <RotateTransform Angle="180"
                                 CenterX="30"
                                 CenterY="26" />
            </Button.RenderTransform>
        </Button>
        
        <StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button Content="Go to Diary"
                    Command="{Binding NavigateToDiaryCommand}"></Button>
        </StackPanel>
    </Grid>
  • The NavigationService already has a property GoForwardCommand that we can access for the navigation.
  • The NavigationToDiaryCommand is the DelegateCommand that we just created on the viewmodel.

4) On DiaryPageVM.cs, we need a way to navigate away from the diary page back to the main page.
This means that we need to implement the IRequireNavigationService on the MainPageVM, so we can access the NavigationService property.

public class DiaryVM : IRequireNavigationService
	{
	    public INavigationService NavigationService { set; get; }
	}

5) On DiaryPage.xaml, we need to add the button to navigate back to the main page and a textbox to put our diary entry.

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <Button HorizontalAlignment="Left"
                Command="{Binding NavigationService.GoBackCommand}"
                Style="{StaticResource BackButtonStyle}">
        </Button>

        <TextBox Grid.Row="1"
                 HorizontalAlignment="Stretch"
                 VerticalAlignment="Stretch" Margin="100"
                 AcceptsReturn="True"/>
    </Grid>

When we run the program, we notice that on the Main Page, there is only one button (center). The reason is there is no instance of diary page yet.
When we click the ‘Go to Diary’ button, it creates the diary page instance, so when we navigate back to the main page, we can see the ‘forward’ button.

Congratulations! You built an app that can be navigated from one page to another.
Here is the link to the whole solution

WinRT Framework: Getting Started

Windows Runtime (WinRT) is used to make Windows store applications. The problem is that the WinRT API is designed in a way that Views and ViewModels are tightly coupled. This means that all the business logic, events like button click, are in “code-behind” of the view instead of it being in the view model. This Framework allows us to enforce a solid MVVM pattern that puts all the business logic in the view model making it decoupled from the view.

Before we make use of the functionalities of the framework, we need to make sure that it is referenced correctly in our project.
To read an in-depth explanation about the framework, refer to this: Introduction of WinRT Framework

1) In Visual Studio, create a new Blank App project
BlankApp

2) Add a reference to the framework
Framework Reference

3) We need to change the base class of the app-class to DefaultApplication. By doing this, the DefaultApplication takes care of the initialization of the framework. This means that the framework will automatically be set up for us. To do this, we need to change <application> tag to <mvvm:DefaultApplication> and we also need to add a namespace: xmlns:mvvm=”using:WinRTFramework.DefaultImplementations”

<mvvm:DefaultApplication x:Class="DemoProject.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mvvm="using:WinRTFramework.DefaultImplementations">

4) Since we changed the base class to DefaultApplication on the xaml, we need to do the same thing in the code behind (App.xaml.cs)
We need the App to inherit from DefaultApplication.

sealed partial class App : DefaultApplication

5) Now, we need to add a new class called MainPageVM.cs. This will become the view model of our MainPage View.

MainPageVM_class

6) Then we implement methods of DefaultApplication:
6a) IsSearchSupported tells the Framework if we support search or not..
For this instance, we will not be doing search so we can just set the value to ‘false’. Down the road, if we want to make an application that supports searching, we can just change the value to return ‘true’

protected override bool IsSearchSupported
	    {
	        get { return false; }
	    }

6b) Next we need to provide the framework with an adapter to our IoC Container, which will allow the framework to create instances from our ViewModels Types. If you use your own IoC Container (such as Autofac or Prism), you should develop an IoCAdapter by implementing the IoCAdapter Interface. If, however, your project does not use an IoC Container, you can use the framework’s DefaultIoCAdapter, which is a very simplistic IoC Container implementation that uses types’ default constructors to create their instances.

protected override IIoCAdapter IoCAdapter
	    {
		  get { return new DefaultIoCAdapter(_viewToVMMap.Values); }
	    }

6c) The framework uses an instance of a IViewViewModelMapper to find out which View belongs to which ViewModel and vice versa. If you follow a fixed naming pattern in your project (such as the ViewModel for Page XYZPage is always called XYZViewModel), you would develop an IViewViewModelMapper which finds matching partners according to this naming rule. If you, however, don’t have such a naming rule, you can use the Framework’s DefaultViewViewModelMapper which accepts an instance of a Dictionary that simply maps the type of a View to the type of a ViewModel

Dictionary _viewToVMMap = new Dictionary();
 public App()
        {
			_viewToVMMap.Add(typeof(MainPage), typeof(MainPageVM));
        }

protected override IViewViewModelMapper ViewViewModelMapper
	    {
		    get { return new DefaultViewViewModelMapper(_viewToVMMap, IoCAdapter); }
	    }

6d) Lastly, we want to tell the framework what page we want to navigate to. We achieve this by specifying in the Navigate() method what ViewModel of the page that we want to navigate to.
This means that if we want to navigate to the MainPage View, we need to specify its view-model to the Navigate method like this — Navigate<MainPageVM>().

	    protected override bool NavigateToInitialPage(INavigationService navigationService)
	    {
		    return navigationService.Navigate();
	    }

Here is the link to the solution