Tuesday, December 16, 2008

Silverlight Page Navigation

Dear all,

When you are new guy in silverlight then you will find the problem how to navigate in silverlight page.

even i am also get stucked in that for this reason i am writing this post to help people like me.

As you see the initial this how the default page set or load in silverlight application then you will answer in App.xaml file and you will find below code.

Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
Me.RootVisual = new Page()
End Sub

It means that when ever application start it shows page.xaml because you have assign RootVisual Page class object.

now what if you want to navigate from a button click to other page like rajat.xaml.

for this you have to right some simple code. like below

first in App.xaml Start up event

Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
Dim tGrid As New Grid()
tGrid.Children.Add(New Page())
Me.RootVisual = tGrid
End Sub

Then On the button click event of Page.xaml you have to write below code

Private Sub btnNavigate_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
Dim tmp = CType(Application.Current.RootVisual, Grid)
tmp.Children.Insert(0, New Rajat()) 'Assign Rajat.xaml page class object to grid child
tmp.Children.RemoveAt(1) ' Remove old page which is page.xaml
Application.Current.RootVisual = tmp 'Assign Root visual again the page which we need to show

End Sub

I hope it will be useful .

Thanks

Rajat