Click here to Skip to main content
15,881,882 members
Articles / Mobile Apps

Getting Started with Windows Phone and MVVM Light - Part 2 of 2

Rate me:
Please Sign up or sign in to vote.
4.80/5 (3 votes)
10 Sep 2012CPOL3 min read 11.3K   3   3
Getting started with Windows Phone and MVVM Light

In Part 1, we covered the following:

  • Creating the application
  • Connecting the View and the View-Model
  • Adding an additional View or Page

In Part 2, we'll see how to add a button on the first page to navigate to the second page which will cover navigation and messaging to complete the application and although basic, will give a rather decent start to create and publish your first Rubber Ducky application.

If you need the code, you can get it here.

Let’s start by opening MainPage.xaml. You should see the following image here:

Add a button by dragging it on to the design surface or adding the following code, it doesn’t matter where, just somewhere within the content grid.

<TextBlock Text="{Binding Welcome}"
			           Style="{StaticResource PhoneTextNormalStyle}"
			           HorizontalAlignment="Center"
			           VerticalAlignment="Center"
			           FontSize="40" />
					   
            <Button Content="Button" 
					Height="72" HorizontalAlignment="Left" 
					Margin="154,354,0,0" Name="button1" 
					VerticalAlignment="Top" Width="160" />

Next, let's add the messaging capabilities which will work hand in hand with the navigation from one page to the next. Start by adding a new folder to the solution called “Messages”.

Then add a new class called NavigateToPageMessage.cs which contains the following code:

C#
public class NavigateToPageMessage
{
	public NavigateToPageMessage()
	{

	}

	public string PageName { get; set; }
}

Now, we have to register the main page of the application to receive the NavigateToPageMessage and do something once it receives it. Open MainPage.xaml and add a new event handler for the Loaded Event. Do this by selecting the PhoneApplicationPage in the Document Outline Window, go to the Properties Windows and select the Events Tab and double click the Loaded event to insert the code.

image

Open the MainPage.xaml.cs code and find the newly inserted event handler which should look like the following:

C#
private void PhoneApplicationPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
	
}

In order to support messaging from MVVM Light, add the messaging namespace (MvvmLight1.Messages;) to the top of the page. Next, we will add the code to subscribe to the NavigateToPageMessage.

C#
private void PhoneApplicationPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
	Messenger.Default.Register<NavigateToPageMessage>
				(
					this,
					(action) => ReceiveMessage(action)
				);
}

ReceiveMessage is the delegate that will handle the message object, in this case the NavigateToPageMessage type.

C#
private object ReceiveMessage(NavigateToPageMessage action)
{
	var page = string.Format("/Views/{0}View.xaml", action.PageName);

	if (action.PageName == "Main")
	{
		page = "/MainPage.xaml";
	}


	NavigationService.Navigate(
	   new System.Uri(page,
			 System.UriKind.Relative));
	return null;
}

What we have done here is handled the property PageName of the action and to the application to navigate to the appropriate page. Pretty simple right? You’ll notice that I put in a special handler here if the PageName is Main to follow the default structure in the MVVM Light template. As a note, I typically move the MainPage into the Views folder and make the adjustments to all of the wiring so that all of my views are in the place where I like them. The next step is to hook up that button we added earlier to send the NavigateToPageMessage when it's clicked. If you have Blend, this portion is drag and drop, otherwise, you’ll have to do some cut and paste. Open the project in Blend, then open MainPage.xaml in the designer. Select the Assets Tab and click on the Behaviors in the left panel. You will see a selection called EventToCommand; click and drag this item to either the Button on the design surface OR the button in the Object and Timeline and release.

image

Then, in the properties tab, give the new EventToCommand the name “GoToPage2”, the EventName should already set to Click, if it is not, change it.

image

Save your changes, and if you view the XAML now, you should see the following code:

<Button Content="Button" Height="72" HorizontalAlignment="Left" Margin="154,354,0,0" 
 x:Name="button1" VerticalAlignment="Top" Width="160" >
	<i:Interaction.Triggers>
		<i:EventTrigger EventName="Click">
			<GalaSoft_MvvmLight_Command:EventToCommand x:Name="GoToPage2" 
             Command="{Binding GoToSecondPageCommand, Mode=OneWay}"/>
		</i:EventTrigger>
	</i:Interaction.Triggers>
</Button>

Next step, back to Visual Studio to add the last bit of code to the MainViewModel. Add a new RelayCommand which is in the MvvmLight.Command namespace.

C#
public RelayCommand GoToSecondPageCommand { get; private set; } 

Then in the constructor in the “else” portion, you need to instantiate the RelayCommand and add the handler to send the message. Add the following code:

C#
GoToSecondPageCommand = new RelayCommand(() => { MessageBox.Show("Going to Second Page now"); Messenger.Default.Send<NavigateToPageMessage>(new NavigateToPageMessage() { PageName = "SecondPage" }); }); 

One last step here is to tell the EventToCommand that we added in Blend that this is the command to execute when the Click event is fired. We do this by setting the Command property in the XAML to the following:

<Button Content="Button" Height="72" HorizontalAlignment="Left" 
Margin="154,354,0,0" x:Name="button1" VerticalAlignment="Top" 
Width="160" > <i:Interaction.Triggers> 
    <i:EventTrigger EventName="Click"> 
        <GalaSoft_MvvmLight_Command:EventToCommand x:Name="GoToPage2" 
            Command="{Binding GoToSecondPageCommand, Mode=OneWay}"/> 
    </i:EventTrigger> </i:Interaction.Triggers> 
</Button> 

Save all and run

GoingTo2ndPage2ndPsge

Click Ok and the next page is presented. Now go build some apps! Download code for Part 2 here.

This article was originally posted at http://blog.tattoocoder.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I work on Azure, ASP.NET Core content and Open Source, speak at national and community events while helping teams architect web and cloud applications.

Comments and Discussions

 
QuestionRubber Ducky aficionado Pin
sbarnes14-Dec-20 19:35
sbarnes14-Dec-20 19:35 
GeneralMy vote of 5 Pin
Kanasz Robert21-Sep-12 0:47
professionalKanasz Robert21-Sep-12 0:47 
GeneralMy vote of 4 Pin
SurfRat19-Sep-12 2:16
SurfRat19-Sep-12 2:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.