Yesterday, somebody asked me how to do conditional navigation in SketchFlow. Out of the box, there is no built-in behavior to do conditional navigation, but the good news is that it is not hard to write one. Here is an example for how to do it.
There are many different ways of doing it. For this sample, it works like this:
- There are two behaviors: SetNavigationTarget and ConditionalNavigation
- SetNavigationTarget takes one property that you set to the display name of the screen you want to navigate to the next time ConditionalNavigation is triggered. You can have as many of these behaviors as you want across your screen – the last one triggered wins.
- ConditionalNavigation navigates to the screen set by the last triggered SetNavigationTarget behavior.
Before I explain the code, here is a screenshot of a minimal sample app using them:
The app has two instances of the SetNavigationTarget behavior. One is attached to the LayoutRoot and set to fire right after loading:
It sets the target screen to “Screen 2”. It is generally a good idea to have one SetNavigationTarget behavior triggered by the Loaded event on every page where you want a default target to be set.
The second instance is attached to the toggle button, and sets the target screen to “Screen 3” when the toggle button is checked.
Finally, the “Navigate!” button on the page has the ConditionalNavigation behavior attached to it, fired by a click of the button.
About the Code
Both behaviors use a little backend object to store state:
This backend object is a singleton. That is, an object that can only be instantiated once, and that is accessible through a global static access property. This is a very simple singleton – all it offers is a single string property to store the desired name of the Target screen.
The SetNavigationTarget behavior is also quite simple: Whenever it is triggered, it just stores the string set as its property in the backend object:
ConditionalNavigation is not really complicated either, but it does have a little twist:
The API function of the player that navigates between screens requires the class name of the screen including its namespace to work. However, this is not the name shown in the SketchFlow Map (you might have renamed the screen, but at the very least, the displayed name is without the name space). In the Invoke() method, there is a little bit of code that walks through all screens present in the prototype and checks if one matches the “nickname” given to the behavior. If it does, the behavior navigates to that screen happily. Otherwise, it does nothing.
Finally, here is the sample project with the sample source code for the two behaviors: