How to navigate in Silverlight?
Last post 05-06-2008 5:08 PM by jmcfet. 27 replies.
Sort Posts:
09-27-2007 6:10 AM
How to navigate in Silverlight?

By managed code or script code or in Html leveL?

 Any Help will be appriciated!

 Thanks!

Annie Zhao

Joined on 09-27-2007
Posts 8
09-27-2007 6:23 AM
Re: How to navigate in Silverlight?

 System.Windows.Browser.HtmlPage.Navigate("url");

is used to navigate to other pages with Silverlight. 

Thanks
Yasser Makram
My Blog: http://www.silverlightrecipes.com
Sr. Architect
Santeon Inc. Microsoft Silverlight Partner, Solution Provider

y_makram

Joined on 06-07-2007
Cairo, Egypt
Posts 1,123
09-27-2007 11:31 PM
Re: How to navigate in Silverlight?

Thanks! 

But if I want to use the same HtmlPage, and change the xaml file, How can I do this?

I try to reset the source of silverlight plugin, but there will be exception.

                            document = HtmlPage.Document;
                            HtmlElement homeSilverlight = document.GetElementByID("SilverlightControl");                                                  
                            homeSilverlight.SetAttribute("source", "MyClasses.xaml");  // exception will be thrown

Annie Zhao

Joined on 09-27-2007
Posts 8
09-28-2007 12:38 AM
Re: How to navigate in Silverlight?

Your main Silverlight control will be a Canvas. Every canvas has a Children collection.If you are coding mostly in XAML, you may not interact with the children collection directly: the elements you put inside the canvas in the XAML get loaded into the children collection automatically.

You can programmatically access the Children collection: when you Add something to the children collection of your main canvas it will appear on the screen, when you Remove it, it will disappear.

I would create a separate User Control for each of the "pages" you want the user to navigate through. Each of the controls will be in a separate XAML file with its own C# code-behind file.

When your main page loads, you can use XamlReader.Load to read in each of the XAML files for each of your user controls. XamlReader.Load builds .net objects from the XAML - basically it gives you back something you can Add/Remove from the Children collection of a Canvas. Now you have every page the user might navigate to loaded into your program and ready to go.

All you need then are a few 'buttons' to let the user choose which 'page' of your application to visit, then you Remove the current page from the Children collection of your main Canvas and Add the new page.

I'll be interested to see if other people here have a simpler way of doing this....


 

MarkTap

Joined on 09-12-2007
Posts 118
09-28-2007 2:03 AM
Marked as Answer
Re: How to navigate in Silverlight?

Hi there,

I am going to share with you now my way of doing these kind of things. Wink

Every page (or say dialog) I use in my application is a custom control derived from the Control class. Generally the constructor loads the corresponding XAML file and initializes the elements. Example:

public class WelcomeDialog : Control
{
    FrameworkElement implementationRoot;
    Rectangle startButton;

    public WelcomeDialog()
    {
        System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("MyAppName.WelcomeDialog.xaml");
        implementationRoot =
this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());
        startButton = (
Rectangle)implementationRoot.FindName("StartButton");
    }
}

To use the dialog in my application I create an instance of it in the main Page code-behind file (Page.xaml.cs) by calling its constructor and add it to the root canvas of the main page. Example:

welcome = new WelcomeDialog(this);  // "welcome" is a member variable of the (main) page class
welcome.Left = (this.Width - welcome.Width) / 2;  // center dialog horizontally
welcome.Top = (this.Height - welcome.Height) / 2;  // center dialog vertically
this.Children.Add(welcome);

To hide the dialog in my application I remove it from the root canvas of the main page. Example:

this.Children.Remove(welcome);

Note: if your dialog has the same size as the main page the user thinks that he sees a new "site".

balla

Joined on 09-06-2007
Posts 200
09-28-2007 4:55 AM
Re: How to navigate in Silverlight?

hello.

just to add that you might be able to change the source of the control but you'll only be able to do that from javascript (shouldn't really do this if the js method is being called by your silverlight control). so, the previous approach looks good to me and you should use it for "changing" the content of your silverlight control

luisabreu

Joined on 04-30-2007
Posts 612
09-28-2007 6:12 AM
Re: How to navigate in Silverlight?

Hey balla, your method works!

I think it's simple and have an advantage that the page's status will be preserved naturelly.

 Thanks a lot!

Annie Zhao

Joined on 09-27-2007
Posts 8
09-28-2007 10:17 AM
Re: How to navigate in Silverlight?

Annie,

Please mark balla's post as the answer to this thread.

jasonxz

Joined on 04-17-2007
Arlington, TX
Posts 490
09-28-2007 10:34 AM
Re: How to navigate in Silverlight?

I agree with balla that letting each control load itself with InitializeFromXaml is simpler than using XamlReader.Load manually like I suggested.

XamlReader.Load works well to load a bunch of separate files into the same control (which is what I've been using it for).

MarkTap

Joined on 09-12-2007
Posts 118
09-28-2007 3:04 PM
Re: Re: How to navigate in Silverlight?

I tried doing this the way Balla said and it worked great.  The only problem is that when I load a Silverlight UserControl by this.children.add(MyUC) I cannot reference objects in the UserControl in the UserControls C# file.  For example, in the UC I have a xaml rectangle with xName of MyRect.  In the constructor of my UC I try to put a mouseLeftButtonDown event on myRect but Intellesense never picks it up.  Any ideas of why this is?  Thanks, V

Sr. Application Engineer
REZN8 Productions Inc.

victorGaudioso

Joined on 05-04-2007
Posts 32
09-28-2007 3:24 PM
Re: Re: How to navigate in Silverlight?

A SL page, like an ASP.NET page, creates a partial class as its code-behind.  The part of the class that you don't see is created based on your XAML and registers fields that represent your controls in your XAML.  That's why they show up in your code-behind.

The UserControl does not work in the same way.  In order to access a control within your UserControl from its code-behind you have to use the FindName(controlName) method.  Now, that method must be called from the root control of your UserControl, which is usually a Canvas.

If you use the InitializeFromXaml method to initialize your UserControl, that method returns an object of type FrameworkElement.  That object would be your root Canvas.

jasonxz

Joined on 04-17-2007
Arlington, TX
Posts 490
09-28-2007 4:10 PM
Re: Re: Re: How to navigate in Silverlight?

Awesome...have any sample code for this?  Thanks!

Sr. Application Engineer
REZN8 Productions Inc.

victorGaudioso

Joined on 05-04-2007
Posts 32
09-28-2007 4:14 PM
Re: Re: Re: How to navigate in Silverlight?

If you look at the control library in the SDK at the ControlBase class, you'll see that it loads the XAML into a FrameworkElement object declared as _root.  Then, it defines a method called FindName() that executes the _root object's FindName method.  So, take a close look at that class.

jasonxz

Joined on 04-17-2007
Arlington, TX
Posts 490
09-28-2007 5:08 PM
Re: Re: Re: Re: How to navigate in Silverlight?

this works:

 

private void InitializeFromXaml()

{

UIElement _btn1 = actualControl.FindName("Button1") as UIElement;if (_btn1 != null)

{

_btn1.MouseLeftButtonDown +=
new MouseEventHandler(myBtn_MouseLeftButtonDown);

}

}

 

Thanks!

Sr. Application Engineer
REZN8 Productions Inc.

victorGaudioso

Joined on 05-04-2007
Posts 32
09-28-2007 5:33 PM
Re: Re: Re: Re: Re: How to navigate in Silverlight?

Actually, in diong this more elegant I created a handly little Method that you can use to do it for you:

private FrameworkElement actualControl;public Section1()

{

System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("SilverlightNavigation.Section1.xaml");

actualControl = this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());actualControl.MouseLeftButtonDown += new MouseEventHandler(actualControl_MouseLeftButtonDown);

 

// create a UIElement called _btn1 and set it to our GetUIElementByName Method

// pass in the actualControl as set from above and the x:Name of the XAML control (which is really just a Rectangle)

UIElement _btn1 = GetUIElementByName(actualControl, "Button1");

// now our _btn1 has all of the events of a UIElement and thus we can now code against it

_btn1.MouseLeftButtonDown += new MouseEventHandler(_btn1_MouseLeftButtonDown);

 

}

 

 

private UIElement GetUIElementByName(FrameworkElement obj, string objName)

{

// find the XAML object my name and cast it as a UIElement and return it

return obj.FindName(objName) as UIElement;

}

 

void _btn1_MouseLeftButtonDown(object sender, MouseEventArgs e)

{

Debug.WriteLine("BUTTON1 Click!");

}

 

Hope this helps anyone with a siliar problem.

 Victor Gaudioso

Sr. Application Engineer
REZN8 Productions Inc.

victorGaudioso

Joined on 05-04-2007
Posts 32
09-28-2007 9:32 PM
Re: How to navigate in Silverlight?

Hi jasonxz, 

I try to mark balla's post as the answer by click the link above the post, but there is no reaction.

Have I succeeded?

Annie Zhao

Joined on 09-27-2007
Posts 8
09-29-2007 1:13 AM
Re: Re: Re: Re: Re: How to navigate in Silverlight?

Hi there,

I meet another problem.

I created the page as a Cuctom Control.But if I add an event handler in the control constructor, then when I add the control to the main canvas as a child, there will be exception. Anyone knows the reason?

public MyClassesCtrl(){

System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("SilverlightGrava.MyClassesCtrl.xaml");

 

this.KeyUp += new KeyboardEventHandler(HandleKeyUp);

}

try{
myClassesFrame = new MyClassesCtrl();
this.Children.Add(myClassesFrame);//exception will throw
}                        catch(Exception ex)

{

string exm = ex.Message;//Massage is: Error HRESULT E_FAIL has been returned from a call to a COM component."}
}
Annie Zhao

Joined on 09-27-2007
Posts 8
09-29-2007 10:02 AM
Re: Re: Re: Re: Re: How to navigate in Silverlight?

Keyboard events only work for your main canvas, not your custom control.
 

MarkTap

Joined on 09-12-2007
Posts 118
09-29-2007 11:24 PM
Re: Re: Re: Re: Re: How to navigate in Silverlight?

Is there any way to let custom control have keyboard events?

Annie Zhao

Joined on 09-27-2007
Posts 8
09-29-2007 11:25 PM
Re: Re: Re: Re: Re: How to navigate in Silverlight?

Is there any way to let custom control to have keyboard events?

Annie Zhao

Joined on 09-27-2007
Posts 8
09-30-2007 12:28 AM
Re: Re: Re: Re: Re: How to navigate in Silverlight?

You can register your handler (i.e. KeyUp += ....) on your main canvas and manually dispatch the event to your control.

The tricky part is figuring out which of your controls should get the event. I think there are a few people on these forums that have some code to help with that - this has come up before, so you could search here for some keyboard discussions.

MarkTap

Joined on 09-12-2007
Posts 118
09-30-2007 3:00 AM
Re: Re: Re: Re: Re: How to navigate in Silverlight?

Thanks MarkTap!

It works well.

Annie Zhao

Joined on 09-27-2007
Posts 8
10-05-2007 1:37 PM
Re: How to navigate in Silverlight?

y_makram:

 System.Windows.Browser.HtmlPage.Navigate("url");

is used to navigate to other pages with Silverlight. 

 

Hi,

When I call HtmlPage.Navigate("http://www.msn.com"), it works. However, when I call HtmlPage.Navigate("../RelativePage.aspx"), the operation fails with a COM exception. It seems like that this method doesn't support relative urls. Is this a known issue? Are there workarounds, besides using Javascript to navigate to other pages?

 Thanks

dsdsico

Joined on 08-28-2007
Netherlands
Posts 42
01-17-2008 11:25 PM
Re: Re: Re: Re: Re: How to navigate in Silverlight?

can u share the code fragment for using keyboard events in custom control

redjackl

Joined on 01-04-2008
Posts 39
03-15-2008 8:05 AM
Re: How to navigate in Silverlight?

 Hi,

I searched while a long time how to navigate in Silverlight2, so I post the code here, maybe could it be helpful Geeked 

Silverlight2 :System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("urlString"));

desopedr

Joined on 02-15-2008
Switzerland, Valais
Posts 29
05-06-2008 3:42 PM
Re: How to navigate in Silverlight?

As stated above this solution will not work if you want to stay in the context of the same HTML page , that is in the same application.  there has to be a simpler way then recommended above where the solutions load XAML from a manifest stream. the code mention does not work in SL2 anyways.

ScottGu shows a possible solution where he plays with the visabilty of the control and that works but surely I am missing the obvious as I have 2 pages in my app and page 1 has a button that will navigate to Page 2 .

 

 

jmcfet

Joined on 04-02-2006
Posts 6
05-06-2008 3:58 PM
Re: How to navigate in Silverlight?

My last post was to navigate to an webpage, not to load XAML.

In a test project I have a MainPage.xaml with a Panel called ContentHolder where I load my XAML pages like this :
 

NavigateToPage("MyNamespace.MyUserControl");
 

public static class Utils
  {
    public static void NavigateToPage(string xamlPage)
    {
      UserControl userControl = Application.Current.GetType().Assembly.CreateInstance(xamlPage) as UserControl;
      if (userControl != null)
      {
        Control root = (Control)Application.Current.RootVisual;
        Panel contentHolder = (Panel)root.FindName("ContentHolder");
        contentHolder.Children.Clear();
        contentHolder.Children.Add(userControl);
      }
    }
  }
 

desopedr

Joined on 02-15-2008
Switzerland, Valais
Posts 29
05-06-2008 5:08 PM
Re: How to navigate in Silverlight?

Thanks for the quick response, I tried what u suggested and CreateInstance is not able to instantiate my control, I must be misunderstanding how this process works as i just added a userControl to my project so it looks like:

Multipages

     MyDialog.XAML

          MyDialog.XAML.cs 

     Page.xaml

           Page.xaml.cs

the XAML for the UserControl looks like:

<UserControl x:Class="MultiplePages.MyDialog"

xmlns="http://schemas.microsoft.com/client/2007"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Width="400" Height="300">

<Grid x:Name="LayoutRoot" Background="White">

<Rectangle Height="50" Width="200" Fill="Black"></Rectangle>

</Grid>

</UserControl>

Pretty simple and  I have a button handler connected to a button on Page that contains:(I am doing this in baby steps)

UserControl userControl = Application.Current.GetType().Assembly.CreateInstance("MultiplePages.MyDialog") as UserControl;

This throws with exception:

An exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll but was not handled in user code

 

jmcfet

Joined on 04-02-2006
Posts 6