×

First time here?

You are looking at the most recent posts. You may also want to check out older archives. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS or email. Thank you for visiting!

This is part 2 in a series on getting started with Silverlight.  To view the index to the series click hereYou can download the completed project files for this sample application in C# or Visual Basic.

Understanding layout management in XAML applications is an important aspect in being successful in Silverlight development.  For most coming from the web world, this will be one of the bigger challenges if you are not a CSS wizard.

Understanding Layout Options

Silverlight provides a flexible system for laying out UI elements on a surface.  There are layout models to support both a dynamic and absolute layout style.  There are several layout controls provided but the most commonly used will be:

  • Canvas
  • StackPanel
  • Grid

Let’s take a look at each of these using elements placed within them to see how they work.  We’ll use a simple Button element to demonstrate the purpose.  We’re using the same project we started with in step 1 and will show these on the Home.xaml page for simplicity (this is throw away code so just pick somewhere to play around for now).

Canvas

The Canvas is the most basic layout and would be used for positioning elements in an absolute manner using coordinates.  You position elements in the Canvas using Attached Properties. Attached properties allow the parent container (in this case Canvas) to extend the property of the controls within it (in our example Button).  We can position several buttons on a Canvas like this:

   1: <Canvas>
   2:     <Button Canvas.Top="50" Canvas.Left="50" Content="Button 1" FontSize="18" Width="150" Height="45" />
   3:     <Button Canvas.Top="150" Canvas.Left="20" Content="Button 2" FontSize="18" Width="150" Height="45" />
   4:     <Button Canvas.Top="70" Canvas.Left="80" Canvas.ZIndex="99" Content="Button 3" FontSize="18" Width="150" Height="45" />
   5: </Canvas>

and when rendered it would show something like this:

Canvas layout

As you can see, this is the absolute positioning approach to layout.  Notice in the code I can also specify an attached property for ZIndex which is why one Button is overlapping the other in this example.  This might be helpful in game development or high physics situations where the calculations are very specific.  Canvas is useful when things don’t move around much or you are pretty in control of the sizing of the application.  Otherwise, Canvas can sometimes be difficult to leverage in favor of things like StackPanel or Grid.

StackPanel

A StackPanel is a layout control which stacks the elements either vertically or horizontally (vertical by default).  Using the sample with 3 Buttons and this code:

   1: <StackPanel>
   2:     <Button Margin="10" Content="Button 1" FontSize="18" Width="150" Height="45" />
   3:     <Button Margin="10" Content="Button 2" FontSize="18" Width="150" Height="45" />
   4:     <Button Margin="10" Content="Button 3" FontSize="18" Width="150" Height="45" />
   5: </StackPanel>

the layout rendered would be:

StackPanel vertical

or if we change the default Orientation attribute to horizontal using this code (notice only difference is Orientation attribute on StackPanel):

   1: <StackPanel Orientation="Horizontal">
   2:     <Button Margin="10" Content="Button 1" FontSize="18" Width="150" Height="45" />
   3:     <Button Margin="10" Content="Button 2" FontSize="18" Width="150" Height="45" />
   4:     <Button Margin="10" Content="Button 3" FontSize="18" Width="150" Height="45" />
   5: </StackPanel>

it would render like:

StackPanel horizontal

StackPanel provides a simple way to layout elements on top of each other or alongside each other without much challenge of worrying about the positioning of the elements within this container.

Grid

Grid is going to usually be the most flexible layout for most scenarios (notice I said most, not all).  It is exactly what it sounds like, a Grid structure using rows and columns.  Unlike what web developers may be used to with the <table> element where the content is within the <tr>,<td> tags, the XAML Grid is different.  You define the overall structure of the Grid and then use attached properties to tell the elements where to place themselves.

Consider this code (notice I’m explicitly showing grid lines but that isn’t something you’d normally do generally…just showing here for better visualization):

   1: <Grid ShowGridLines="True">
   2:     <Grid.RowDefinitions>
   3:         <RowDefinition Height="60" />
   4:         <RowDefinition Height="60" />
   5:         <RowDefinition Height="60" />
   6:     </Grid.RowDefinitions>   
   7:     
   8:     <Grid.ColumnDefinitions>
   9:         <ColumnDefinition Width="175" />
  10:         <ColumnDefinition Width="175" />
  11:         <ColumnDefinition Width="175" />
  12:     </Grid.ColumnDefinitions>
  13:     
  14:     <Button Grid.Column="0" Grid.Row="0" Content="Button 1" FontSize="18" Width="150" Height="45" />
  15:     <Button Grid.Column="2" Grid.Row="0" Margin="10" Content="Button 2" FontSize="18" Width="150" Height="45" />
  16:     <Button Grid.Column="1" Grid.Row="2" Margin="10" Content="Button 3" FontSize="18" Width="150" Height="45" />
  17: </Grid>

We are defining the Grid to have 3 columns and 3 rows with specific width and heights.  Notice then in the Button elements we are positioning them in specific places within the Grid using the attached properties.  The resulting rendering looks like this:

Notice how the attached properties on the Button (Grid.Column, Grid.Row) tell the element where to position itself within the container.  Working with layouts is where Expression Blend can be extremely helpful.  Notice how in Blend you can use the guides to specify the column/row definitions visually and it will generate the XAML for you:

Grid in Blend

The arrows show you the guides as well as a visual indicator if the row/column are a fixed size (the lock).  We’ll use a combination of layout controls in our application.  In fact, the default template we chose makes use of all the different types of layout controls already for our basic shell for our application.

Building our Twitter Application

Now we can start building out our application.  In general, this is the mockup that we’ll be going after:

Twitter app mockup

Notice that we’ll have a place for the user to enter a search term, and the results will display in some list layout.  We’ll also have navigation areas to go to different views such as previous search term history and possibly some statistics.

Luckily the navigation template we chose already gives us some heavy lifting of our overall layout.  In MainPage.xaml I’m going to make a few changes.  On about line 29 in MainPage.xaml, I’m removing the application logo, and then changing the ApplicationnameTextBlock below it to “Twitter Search Monitor” for my application.

We’ll get back to navigation in a minute, but let’s recreate our Views.  In the project structure in the Views folder, create a new Page by right-clicking in Visual Studio and choosing to create a new Silverlight Page and name it Search.xaml:

Add Silverlight Page dialog

Now you should have a blank XAML page with a default Grid layout.  This is where we’ll create the search screen seen above.  We get the header information from our MainPage.xaml because we are using a Frame element to host our navigation.

Silverlight Navigation Framework

At this point let’s take a tangent and understand the Silverlight navigation framework.  If you recall we started using the navigation application template.  The default template gave us MainPage.xaml and some views of Home, About.  The navigation framework is fundamentally made up of 3 parts: UriMapper, Frame and Page. 

UriMapper

I like to think of the UriMapper element as a routing engine of sorts.  It is not required by any means but I think obfuscates and simplifies your navigation endpoint.  Instead of exposing the literal /Views/Home.xaml URI endpoint, you can map that to a simpler “/Home” endpoint that is more readable and doesn’t give away and technical configuration…and can change later to map to something else.  You can see the UriMapper as an element of the Frame in MainPage.xaml:

   1: <navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}" 
   2:                 Source="/Home" Navigated="ContentFrame_Navigated" 
   3:                 NavigationFailed="ContentFrame_NavigationFailed">
   4: <navigation:Frame.UriMapper>
   5:   <uriMapper:UriMapper>
   6:     <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
   7:     <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
   8:   </uriMapper:UriMapper>
   9: </navigation:Frame.UriMapper>
  10: </navigation:Frame>

Now this UriMapper is in XAML like above, but it could also have been a resource and if done that way then you would add it to the Frame element like this (assuming the resource was UriMapperRoutes):

<code/>

We’ll stick to keeping what the template has provided us though at this time.

Frame

If you are an ASP.NET developer, you can think of the Frame element as like the ContentPlaceholder control.  The Frame is the area defined as the area that can be navigated.  You would specify a default view but then any navigation can occur within that area which we will see later.  Looking at the code above, you can see that the default view, the Source attribute of the Frame, is the “/Home” route for our application.

Page

The final fundamental area of navigation is the Page element, which we just created in our last step.  These are basically the content areas that are displayed in the Frame element.  They are very similar to the basic UserControl element that you might normally add (what MainPage is), but are special in that they can interact with navigation.  We will consider our Views in our application as our Page elements.

You can learn more about navigation specifically in this video walk-through:

It’s fairly simple to understand once you dig around in it and can be powerful to use.  This framework is what allows deep-linking into Silverlight applications to exist.

Creating the UI layout for our search view

Let’s finish creating the UI in our Search.xaml page we just created.  At this point you may be wondering what all the {StaticResource XXXXXXXX} elements are in the XAML.  We’ll get to that in the styling/templating section in step 5, so try not to let it bother you for now.

Looking at our mockup, we are going to need a text input area, button and data display grid.  Let’s start laying that out using Blend in our Search.xaml page.  To do this, from Visual Studio, right-click on the Search.xaml page and choose Edit in Expression Blend:

Open in Blend dialog

Since Blend and Visual Studio share the same project structures you will be able to open the file at the same time to do the visual editing of the XAML before we start coding away.

While in blend we’ll layout our Grid to have 2 rows, one for the search input/button and the second for the results view.  In the top row we’ll drag a StackPanel in there and add a TextBox and Button into the StackPanel, setting it for Orientation=Horizontal.

The next thing we’ll do is add a DataGrid to show our data.  Since DataGrid is not a core control, it is in the SDK libraries and we’ll need to add a reference to it.  You can do this in various ways.  Blend will actually do this automatically for you.  In the toolbox pallette for Blend, click the double arrow and search for DataGrid:

Add DataGrid

Once you see it, select it and drag it into the second row.  This automatically added the reference to the System.Windows.Controls.Data.dll for you and changed the markup in the XAML:

   1: <navigation:Page 
   2:            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   4:            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:            mc:Ignorable="d"
   7:            xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
   8:            xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="TwitterSearchMonitor.Views.Search"
   9:            d:DesignWidth="640" d:DesignHeight="480"
  10:            Title="Twitter Search Page">
  11:     <Grid x:Name="LayoutRoot">
  12:         <Grid.RowDefinitions>
  13:             <RowDefinition Height="32"/>
  14:             <RowDefinition/>
  15:         </Grid.RowDefinitions>
  16:         <StackPanel HorizontalAlignment="Left" Margin="0,-32,0,0" VerticalAlignment="Top" Grid.Row="1" Orientation="Horizontal">
  17:             <TextBox x:Name="SearchTerm" FontSize="14.667" Margin="0,0,10,0" Width="275" TextWrapping="Wrap"/>
  18:             <Button x:Name="SearchButton" Width="75" Content="SEARCH"/>
  19:         </StackPanel>
  20:         <data:DataGrid x:Name="SearchResults" Margin="0,8,0,0" Grid.Row="1"/>
  21:     </Grid>
  22: </navigation:Page>

Notice the xmlns:data in the top.  This is how, after adding a reference to the assembly, you add non-core controls to the XAML.  Then to use them you’ll see the data:DataGrid element in the Grid.  Your XAML now should look a bit like mine and visually it looks like this:

Final initial layout

Notice in the XAML that I gave x:Name’s to my TextBox (SearchTerm), Button (SearchButton) and DataGrid (SearchResults).  This will help us later easily program against these elements.

Now if you go back to Visual Studio you may see a prompt to reload the project.  This is because Blend altered the project file by adding a reference to the DataGrid control.  You can go ahead and reload it.  This shows how integrated the tools are at the project file level.  Now we can start coding again using VS.

Changing our UriMapper to default to Search.xaml

Now that we just created the Search page (which is essentially our home page of the application), let’s make a few changes to the navigation framework.  In MainPage.xaml find the Frame and make a few changes to change the default from Home.xaml to our Search and making some other default changes as well.  Your Frame XAML should now look like this:

   1: <navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}" 
   2:               Source="/Search" Navigated="ContentFrame_Navigated" NavigationFailed="ContentFrame_NavigationFailed">
   3: <navigation:Frame.UriMapper>
   4:   <uriMapper:UriMapper>
   5:     <uriMapper:UriMapping Uri="" MappedUri="/Views/Search.xaml"/>
   6:     <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
   7:   </uriMapper:UriMapper>
   8: </navigation:Frame.UriMapper>
   9: </navigation:Frame>

Because we don’t need the Home.xaml anymore, go ahead and delete it from the project.  Also add a new view called History.xaml and alter the MainPage.xaml LinksBorder area to include a link to that:

   1: <Border x:Name="LinksBorder" Style="{StaticResource LinksBorderStyle}">
   2:     <StackPanel x:Name="LinksStackPanel" Style="{StaticResource LinksStackPanelStyle}">
   3:  
   4:         <HyperlinkButton x:Name="Link1" Style="{StaticResource LinkStyle}" 
   5:                          NavigateUri="/Search" TargetName="ContentFrame" Content="home"/>
   6:                          
   7:         <Rectangle x:Name="Divider1" Style="{StaticResource DividerStyle}"/>
   8:         
   9:         <HyperlinkButton x:Name="Link2" Style="{StaticResource LinkStyle}" 
  10:                          NavigateUri="/History" TargetName="ContentFrame" Content="history"/>
  11:                          
  12:         <Rectangle x:Name="Divider2" Style="{StaticResource DividerStyle}"/>
  13:  
  14:         <HyperlinkButton x:Name="Link3" Style="{StaticResource LinkStyle}" 
  15:                          NavigateUri="/About" TargetName="ContentFrame" Content="about"/>
  16:  
  17:     </StackPanel>
  18: </Border>

Now our rendering if we run it should look like this:

Final layout rendered

Now that we’ve got the basics of the layout, let’s start adding data in part 3.


This work is licensed under a Creative Commons Attribution By license.


Gravatar
10/6/2009 1:19 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
How do you change the logo instead of remove it?
10/6/2009 2:17 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Tim -- I assume you mean the little arrow logo looking thing in the default template? That is a part of the ApplicationName style template (it is a Path) and I just deleted it.
Gravatar
10/7/2009 5:07 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Yep, that's the one. But lets say I want to replace it with my own logo, rather than delete all together.
10/7/2009 7:51 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Tim -- this is where using Blend to edit the style would come in handy for you. Look at the Assets/styles.xaml file and look for the ApplicationBrand/Logo (can't remember it right this minute) and change the XAML there to be whatever you want. Alternatively if you open the project in Blend you can edit the resources using a UI design surface.
10/8/2009 12:43 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Half way Part 2: Having two questions: How come that when I copy and paste in your Canvas example code into Home.xaml in between </StackPanel> and </ScrollViewer> I get these warnings that property 'Content' is set more than once?
Also if I put ShowGridLines="True" within <Grid ....> I don't see (after I Build the project TwitterSearchMonitor) any visible grid of the Testpage.html in my browser.
Thanks!



10/8/2009 1:11 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
PeterNL - where are you putting the Canvas code? It would have to be *within* StackPanel. The error message you are getting means that you have the XAML (content) within a Panel that only has one placeholder for Content. For the Grid issue, I'd love to see your full XAML.
10/8/2009 1:29 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Here is my XAML code (added to Home.xaml from Part 1):

<Grid x:Name="LayoutRoot" ShowGridLines="True" >
<ScrollViewer x:Name="PageScrollViewer" Style="{StaticResource PageScrollViewerStyle}">

<StackPanel x:Name="ContentStackPanel">

<TextBlock x:Name="HeaderText" Style="{StaticResource HeaderTextStyle}"
Text="Home"/>
<TextBlock x:Name="ContentText" Style="{StaticResource ContentTextStyle}"
Text="Home page content" />
<Button Content="Click me" x:Name="MyButton" FontSize="18" Width="150" Height="45" />

</StackPanel>

<Canvas>
<Button Canvas.Top="50" Canvas.Left="50" Content="Button 1" FontSize="18" Width="150" Height="45" />
<Button Canvas.Top="150" Canvas.Left="20" Content="Button 2" FontSize="18" Width="150" Height="45" />
<Button Canvas.Top="70" Canvas.Left="80" Canvas.ZIndex="99" Content="Button 3" FontSize="18" Width="150" Height="45" />
</Canvas>

</ScrollViewer>

</Grid>
10/8/2009 1:34 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
PeterNL -- okay, thanks for this. Even though you have ShowGridLines enabled, you have no row/column definitions set. Notice in the sample how I set the definition for the rows/columns. Absent of this imagine yourself only having one "cell" area that everything is fitting in.

ScrollViewer can only have one element of content -- and you have two: StackPanel and Canvas. But the Canvas *in* the StackPanel and you'll see it.
10/9/2009 10:50 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Is intellisense the only way to learn the Properties of a control behaviour or a concise document is available to comprehend the possibilities e.g XAML options. Pls suggest any publication, i am reading david yack book but that is a starter.
10/9/2009 11:32 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Thanks TIm - Clear explanation on how these things work inside.
10/9/2009 11:35 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Shankar - look at the Offline CHM Documentation file referenced in the first set of links here: timheuer.com/.../...d-what-is-new-and-changed.aspx
10/9/2009 8:12 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim,

I am implmenting the application in part 2 that requires DataGrid. Data Grid is not included in the downloads of Silver Light 3 and it was not includedd with Blend 3.

Can you tell me where I can geet a download thaat will install in Blend3.

Thanks!!!

Howard
10/16/2009 3:07 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Howard - DataGrid is a part of the SDK which if you installed the Silverlight Tools, you already have. You can add a reference in Visual Studio to System.Windows.Controls.Data.dll. Expression Blend trial can be installed from the links in step 1.
10/16/2009 3:26 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Dipak - using the video code (which was beta code) you need to add a "/" as the message indicates to the UriMappings.
10/24/2009 9:50 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Thanks a lot Tim, it's helping me well to learn Silverlight!!!
Gravatar
10/25/2009 8:47 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Tim,

Why is the StackPanel placed in Grid.Row 1 on the Search page. Seems like it would be in Grid.Row 0 based on the way the buttons were treated at the top of this section.

Thanks
10/27/2009 8:40 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
hey cool amazing! wow
Gravatar
10/28/2009 7:10 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim,
Is there a reason you have the StackPanel in Grid.Row=1 with a top margin of -32, rather than having it in Grid.row=0 and top margin 0. Visually it sits in Row 0.
Thanks
10/28/2009 8:04 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
VJ -- good catch. That must have been when I was moving things around in Blend. Your assumption is correct as to what it should be.
Gravatar
10/28/2009 8:53 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Thanks, Great tutorials BTW and I love the video supplements. Just watched the WCF/asmx one. Cleared up a bunch of things.
10/30/2009 8:05 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
The stackPanel in Search.xaml Grid.Row = 1 should be 0
11/3/2009 2:28 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
I have a very long list and would like to display it as three or four columns. I've already bound it to a ListBox, but it just a long list. How do I get it to display as a 4 x 30 array of items?

Thanks in advance.
11/4/2009 2:30 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim,

great tutorial. Do you know of ways to place controlls like combos and tabcontrolls dynamicaly at runtime on a canvay like with "canvas.left" or "canvas.top". I tried this but those properties seem to be unnknown.

Thanks alot.
11/4/2009 5:35 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
...
Got it. ;)

After creating the controls, it's

...
Canvas.SetLeft(ojectname, pixelvalue);
Canvas.SetTop(ojectname, pixelvalue);
...

Thanks
11/4/2009 8:11 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Found my answer. Using a wrappanel in the list box template.
11/9/2009 2:12 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
I tried running the site but the Search page doesn't show. it still shows the old Main page. any suggestion?
11/9/2009 3:01 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
rico -- review the text in 'changing our urimapper to default to search' again. Look at the Source of the navigation frame and make sure you're setting that correctly.
11/10/2009 2:23 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi

I am really sorry as this will be out of context .. but you seem to be the only person i think i can ask this.

We are a tiny indian company making office erp applications in VB since 1999. Currently we are using VB.Net 3.5 and SQL Server 2005. We have been planning to switchover our applications from .NET 3.5 Windows Applications to a web based platform.

We need lot of complex validations and unbound user controls on our forms. We can do without the printer support, as we can use the "Download XL report" as you demonstrated in one of your examples.

I have 2 questions.

1. Do you think Silverlight is stable enough to switchover for such projects (once again - unbound controls and validations)
2. Do you think C# will be better than VB for getting around in Silverlight.

Thanks in advance ..

Most of the samples i see in silverlight are in C#. Even though it is not difficult to switch over from VB, i am not able to take that leap of faith.
11/10/2009 4:17 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Henu - hard to tell without seeing your application to give you a definitive answer if Silverlight is the right platform for you. In general I can say that I believe Silverlight is ready for business application development. As to C# or VB...you should use what your team is most productive in. All samples provided on http://silverlight.net/learn/ from Microsoft are provided in C#/VB.
11/10/2009 4:36 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Mark M -- you can have only one child in your app.resources, put your UriMapper resource *in* the styles.xaml file.
11/21/2009 12:14 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi,
how to enable scroller to restrict menu to not touch logo. If I resize the window than at one point the menu overlap the logo. Can we handle this in silverlight? I am newbie in this teritory.

Regards,
Emran
11/28/2009 3:18 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi everyone
I found a very strange error when following this tutorial. Sorry cannot remember the exact message (something like a text mismatch) but was in line 14 of ErrorWindow.xaml.vb,

ErrorTextBox.Text = "Page not found: \" + uri.ToString() + " \ """

caused by an extra quote mark after \" in the above(I think). Once deleted all was well.

Regards
david

12/4/2009 10:16 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
When this article talks about using Expression Blend to edit the Search.xaml file, it reminds me of Steve Martin's old joke about telling people how to make a million dollars and not pay taxes:

"First...get a million dollars....THEN!.....DON'T PAY TAXES!!!"

IOW, it doesn't tell you just how to add the rows in Expression Blend...I 2-clicked the grid to add that, but searched through the properties pane and the various menu items (the grid's context menu item first) to see how to do that, but didn't see anything.

I know I can just add them in code (xaml code), but if that's the way to do it, what's the advantage of using Blend over VS?
12/4/2009 10:31 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
So, since I didn't know what to do in Expression Blend, I copied the xaml from this article and pasted it

into VS, namely this:

<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="32"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel HorizontalAlignment="Left" Margin="0,-32,0,0" VerticalAlignment="Top" Grid.Row="1" Orientation="Horizontal">
<TextBox x:Name="SearchTerm" FontSize="14.667" Margin="0,0,10,0" Width="275" TextWrapping="Wrap"/>
<Button x:Name="SearchButton" Width="75" Content="SEARCH"/>
</StackPanel>
<data:DataGrid x:Name="SearchResults" Margin="0,8,0,0" Grid.Row="1"/>
</Grid>

Then, though, the IDE gave its best impression of a nuclear meltdown and informed me:

1)
The attribute 'Class' from the XAML namespace is only accepted on the root element.

2)
The type 'data:DataGrid' was not found. Verify that you are not missing an assembly reference and

that all referenced assemblies have been built.

3)
The type 'Page' does not support direct content.

I thought I might be able to solve problem/error #2 by adding System.Windows.Controls.Data to my "References" folder. The "Add Reference" dialog, however, is completely blank on the .NET tab...?!?
12/4/2009 4:47 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
B. Clay -- if you simply cut/paste you are missing a lot.

1) You need a class for this file...it sounds like it is missing (or different) -- or you copied the entire UserControl contents within the Grid contents.

2)Notice the data:DataGrid -- and notice above in this tutorial after I noted how you can drag/drop the DataGrid in Blend -- *what* that does. I make note of the xmlns:data namespace in the xaml -- that is what you need in addition to the reference.

3) I really am thinking you have bad XAML -- your cut/paste is being done in the wrong places :-) -- without seeing the whole XAML it is hard to tell where you put things.

You can download the completed project and compare.
12/4/2009 4:48 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
B. Clay -- fair point about the grids -- I could be more clear -- you can see other videos on http://silverlight.net/learn on various detail drill-downs on things like this. Blend is a better layout management tool (in my opinion) as well as the ability to perform animations and styling (as you'll see in the later parts of the tutorial).
12/14/2009 6:01 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim, this is an easy one but I can't see that anyone has mentioned it yet.

Under your UriMapper section, it looks like you intended to display the code that you would use to wire up the mapper to the frame manually. I just see an empty tag.

Sorry I couldn't give you a question that would stretch your skills more than this :-)
12/14/2009 9:47 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Andrew -- oops :-) good catch, I'll update it when I get a moment -- I think it is correct in the code download.
12/16/2009 3:31 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
1. App.xaml error in uriMapper: "The property 'Resources' is set more than once"

1. The type 'uriMapper:UriMapper' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.
2. 'uriMapper' is an undeclared namespace.

part of this is error :

<uriMapper:UriMapper>
<uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
<uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
</uriMapper:UriMapper>

why should i do cos at the Refrences : System.Windows.Controls and System.Windows.Controls.Navigation include in my project
help me please to resolve this problem..
thank you
12/16/2009 8:50 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
GM - make sure you have the proper xmlns declaration in the resource.
12/16/2009 10:24 AM | # uriMapper
hi Tim.. sorry I mean what should I do? not "why".. :) . I've checked the xmlns and declare according to your suggestion but why keep errors on <uriMapper: UriMapping ......... > How I can continue to other parts of part 2 while the error still occurs. Could you kindly sent file on part 2 to me because on this error I need 2 hours but not yet resolved. :).. thanks
12/16/2009 11:27 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Gm -- have you downloaded the solution files at the top of each of these tutorial posts -- all the code is provided there.
12/16/2009 11:39 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
I'm sorry I'm not see more detail on this page that you included the code of sample to part 2.. sorry' question maybe bother you. :) I'm so sorry..
12/16/2009 11:41 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Gm -- yeah there is a link to the code at the top of each part of the tutorial. It is the finished product.
12/16/2009 12:55 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
thank you. " Great tutorial "finally I can learn and continue the project. your site was very helpful.
12/16/2009 12:58 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
yeah that's right yakub.. great for our tutorial.. let's go to lesson 3.. thanks Tim
12/20/2009 7:31 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Thank you Tim. Your work is brilliant!!
12/22/2009 4:02 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Great tutorial...:-).. Thanks a lot Tim.
1/1/2010 9:22 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
I'm wondering, in which tool you sketched the mockup?
1/13/2010 5:23 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Thanks for the great tutorial Tim!
1/20/2010 4:09 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
This tutorial is impossible to follow. What are the specific steps that we need to follow? You are all over the place with your instructions. What do we do after we open the search.xaml file in Blend? You talk about grids and rows, but what appears in Blend is a blank pallette. Sorry, I'm sure you are very bright, but I can't follow this tutorial :(
2/3/2010 7:44 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Your tutorial is great ! I finished the Step 1 successfully using VS 2010 Beta2 ! However, I'm struggling to create a new XAML page under the 'Views' folder using VS 2010 Beta 2. My installed templates do not include "Silverlight Page", what template should I use instead. Any help is appreciated.
2/3/2010 8:08 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Suguna -- make sure you've installed the Silverlight Tools for Visual Studio.
2/14/2010 5:44 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Tim,
Great tutorial. I'm going to do them all, buy books, etc. Comments on the tutorial:
1) Blend has a learning curve. I was unable to get all the positioning correct and ended up copying and pasting your XAML. In particular, I noticed that Blend does not insert the StackPanel into the row1 of the Grid and sizing renders unexpected results. Perhaps I'll get it when I do the tutorial on blend.

2) It took me a bit to find out how to add rows to the Grid in the first place. You may want to add a blurb on how to do that in your tutorial... just a suggestion.

Now, with respect to Silverlight, I'm getting ready to do a personal project that would involve Online Education. The site will need to be secured with rights to classes on a per student basis and be able to accept payment. I see that Web service integration is a part of Silverlight. Does this kind of app seem like a fit for a Silverlight implementation (your high level "yes" or "no" is fine with that "detailed" description I just gave)? I'm talking a full functional ecommerce app...

What, if any, books can you recommend? Or is there enough online material I can plow through?

Whew! I'm done for now.

Thanks Tim,

Evan
2/16/2010 4:36 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim, I am using Silverlight 4 (beta) because we will be using features from it. When I tried to build your sample it had errors because it couldn't find some classes. It couldn't find converters:DateTimeConverter and activity:Activity. Do you think that is because of SL4? (I am on Windows 7, VS2010 and .NET4). Is there something else I am missing?
Thanks, and thanks for these tutorials. They are extremely helpful.
Valerie
2/28/2010 9:15 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim,
Thanks for the tutorials!

In the section on UriMapper, did something go missing? Where you describe how to add the UriMapper to the Frame element if it were a resource, it just says

2/28/2010 9:19 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
oops, it didn't take the tag as literal (how did other people get xml in their posts?). That was supposed to say it just shows a code tag.
3/1/2010 11:39 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Is there anything lost in UriMapper section to raplace the tag(before the sentence: We’ll stick to keeping what the template has provided us though at this time.)
3/15/2010 9:52 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim, I am using Silverlight 4 (beta) because we will be using features from it. When I tried to build your sample it had errors because it couldn't find some classes. It couldn't find converters:DateTimeConverter and activity:Activity. Do you think that is because of SL4? (I am on Windows 7, VS2010 and .NET4). Is there something else I am missing?
Thanks, and thanks for these tutorials
3/22/2010 7:02 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Can't add stack panel in Blend. When added in Visual Studio, Blend throws error Invalid XAML.
4/14/2010 4:52 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi,

At one step i had right click and selected Open with Expression Blend. It is trail version. Expression blend is not supporting to open my project. Is there any specific reason? How can i continue to further step?
I am using VS2010 beta. and Silver Light Beta.
4/14/2010 8:20 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Raja -- if you are using VS2010 then you need Expression Blend 4 for the project files to be compatible.
4/17/2010 11:40 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
great work..
4/22/2010 6:23 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Tim-

It is a great tutorial. Question I am using visual studio 2010 when adding this line of code <data:DataGrid x:Name="SearchResults" Margin="0,8,0,0" Grid.Row="1"/> get an error I tried refering and still getting an error.

4/22/2010 6:58 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Elliot -- what error are you getting? DId you make sure to add the xmlns:data notation in the page?
5/7/2010 4:50 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
The problem is that Blend is wiping out the xmlns:data line in Search.xaml every time you rebuild it ;)
5/13/2010 3:21 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Tim-

I'm new to Blend. This is my first time using it. I get to the part where we are going to add our datagrid to the project and you say "drag it to the second row". I can't for the life of me figure out what you're talking about. Could you give me an idea what I'm supposed to be doing? When I open everything in blend, I have an empty box in the middle outlined in blue.

Thanks.
5/13/2010 3:30 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Duh. Nevermind. Figured out what you meant.
5/27/2010 3:36 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim,

Thank you for the great tutorial. I am not sure if this is the right place for this question but I am giving it a shot:

I am only starting with silverlight and would love to use it at my company. Would you recommend using silverlight to download data from a usb device and upload to the cloud? Can you install device drivers when running the silverlight app for the first time? Is WPF with clickonce a better (the right) solution? I am not sure what technology stack to use. I am new to WPF and silverlight (winforms background). Thanks
Gravatar
5/28/2010 8:51 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Tim--

Your lack of any guidance for what to do in Blend is very surprising for a highly visible "Getting Started" tutorial. Most people running through this have never opened Blend before (or they wouldn't be going through your tutorial). A little step-by-step guidance would take you 5 minutes and would save a lot of people some frustration.

Dan
6/9/2010 10:33 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Doesn't compile.

Error:

Error 1 TwitterSearchMonitor The "ValidateXaml" task failed unexpectedly.
System.IO.FileLoadException: Could not load file or assembly 'file:///C:\Users\Adam\Testbeds\Silverlight\TwitterSearchMonitor_CS\TwitterSearchMonitor\Libraries\ActivityControl.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
File name: 'file:///C:\Users\Adam\Testbeds\Silverlight\TwitterSearchMonitor_CS\TwitterSearchMonitor\Libraries\ActivityControl.dll' ---> System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadFrom(String assemblyFile)
at Microsoft.Silverlight.Build.Tasks.ValidateXaml.XamlValidator.Execute(ITask task)
at Microsoft.Silverlight.Build.Tasks.ValidateXaml.XamlValidator.Execute(ITask task)
at Microsoft.Silverlight.Build.Tasks.ValidateXaml.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask, Boolean& taskResult)


6/9/2010 11:12 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Adam -- if this is from the download make sure you 'unblock' the file before unzipping (right-click choose properties and unblock)
7/28/2010 10:59 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
so I have a comment similar to Evan Bonnett's

" I was unable to get all the positioning correct and ended up copying and pasting your XAML. In particular, I noticed that Blend does not insert the StackPanel into the row1 of the Grid and sizing renders unexpected results. Perhaps I'll get it when I do the tutorial on blend"

I basically did exactly the following
a. create a new item -> silverlight page called serach.xaml
b. opened item in expression blend.
c. at this point I have a grid by default called layout root.

my question is now how do I set the properties for the grid. there is nothing in the blend designer to set it up so that it has two rows. I had to copy the xaml from your source onto my .xaml file in-order to get the 2 rows.

In fact I even found that it was easier to do this in visual studio by just adding rowdefinitions to the rowdefinitions collections property on the grid.

is there an easy way to define rowdefinitions in expression blend.
9/14/2010 9:59 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
I'm going thru step 2 and when I run the app I get XamlParseException: Invalid attribute value for property Style. [Line: 30 Position: 43] this error opens MainPage.xaml.cs and the error seems to point to IntializeComponent(); below:

namespace TwitterSearchMonitor
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
Gravatar
10/10/2010 7:44 PM | # Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
In the second step of the tutorial you say to use Blend but provide no instruction on how to use it. I opened up Blend and have no idea what to do. I tried clicking around but ended up with a mess. A reader of this tutorial wouldn't have used Blend before. I don't even know what it is. Can't you include a few steps on what to do?
2/22/2011 7:21 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
2/23/2011 12:29 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi,
I m having a navigation frame and i m lodaing some content pages inside it but some time my content page needs to have more controls on it then i m facing issues,could u guide me how can i display more data in content pages?
2/24/2011 10:14 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
I'm really enjoying reading your well written articles. I spent many efforts and time to update the blog. I'm taking a mark and look forward to reading new articles. Please keep the good articles!
designer watches online | discount replica watches
2/24/2011 10:40 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hi Tim,
I m having a navigation frame and i m lodaing some content pages inside it but some time my content page needs to have more controls on it then i m facing scroll issue eventhough i m using a scrollviewr around the navigation frame but still navigation frame does not display the entire content page,i just tried by increasing the navigation frame length but i dint find a good result,could u give a solution plz?
Gravatar
2/28/2011 11:33 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Creating layout is my favorite part of working online..
Joomla Template
3/1/2011 7:31 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
3/3/2011 4:00 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Games Lovers this is for you download games for free
3/8/2011 8:54 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
4/9/2011 5:45 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
I am silky to uncovering so fruitful structural noesis here in the being, we obligation add often strategies in this precept, thanks for arrangement.
happy birthday
Gravatar
6/13/2011 7:41 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
I think that this part of the blog is rather badly edited. This should be done again with mistakes corrected.
7/9/2011 3:10 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
When adding the grid in blend I get <sdk:dataGrid> rather than <data:datagrid>. The SDK version does not add anything regardign a reference to a dll. Does this matter? Whats the difference between the two?

Thanks, great tutorial!
7/13/2011 6:17 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
wow that was interesting! thank you so much!

finnisch übersetzung

7/19/2011 11:38 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hii,

i was going through your tutorial and its just amazing.I recently started devolopment of a dashboard using Silverlight but my manager tells me to study and understand Silverlight,C# and all these things before I start.

How do i go about it because it is such a wide area to learn and im getting stuck at many a points and I believe unless i know what to design i should not randomly start with a langauge.

Help Me Out PLz!!!
7/28/2011 12:19 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
"HI..I m having a navigation frame and i m loading some content pages inside it but some time my content page needs to have more controls on it then i m facing issues,could u guide me how can i display more data in content pages? " @zahir Can you explain your question further?
Bed Bath And Beyond Printable Coupon
8/1/2011 9:41 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
HI..I m having a navigation frame and i m loading some content pages inside it but some time my content page needs to have more controls on it then i m facing issues,could u guide me how can i display more data in content pages?
Round Rock Window Contractor

8/30/2011 4:39 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Hello Tim,

I have a question regarding the navigation page style, im using the template for my application and i have five different navigation pages. So when i navigate to any one of my pages i do get a gaaps left n right and slightly at top after the header. My question is how do i auto resize the content frame size to fit to the window completely.
9/5/2011 5:43 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
Thanks Tim. A very well written piece here. dorgard
9/7/2011 10:43 PM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
This site is very informative i love to read comment over here.
boxing gear
10/13/2011 2:37 AM | # re: Getting started with Silverlight: Part 2 - Defining the UI layout and Navigation
All post are very clear and sophisticated over here..Thanks for sharing this with us..
curly hair
11/16/2011 9:33 PM | # an error
The type 'sdk:DatePicker' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

 
Please add 3 and 7 and type the answer here:

DISCLAIMER:

The opinions/content expressed on this blog are provided "ASIS" with no warranties and are my own personal opinions/content (unless otherwise noted) and do not represent my employer's view in any way.