Justin Toth's Blog

Justin is a web developer living in Maryland

Silverlight 2 Navigation

clock May 18, 2009 00:51 by author Justin Toth

I've been working on a Silverlight 2 application for the past week and a half and having started my Silverlight experience with SL3, I took for granted the nice navigation features. With SL2 I was forced to create my own navigation framework, which turned out to be a pain in the butt. I read some solutions on the web but they either weren't nice and clean or they assumed that you wanted to navigate from page to page without having a "master" page. It was at this point that I decided to take a crack at it myself...

The first thing I did was create my Page.xaml, which is my master page. In here I created a StackPanel to hold the usercontrol of the current "page" that the user is on. Alternately instead of dynamically adding usercontrol objects to the StackPanel, you could create a UserControl and set its Content property to the user control of the current page.


 <StackPanel x:Name="spContent" Orientation="Vertical" Margin="10,10,10,10" HorizontalAlignment="Left" />

The next thing I had to do was create a Navigate method in the code-behind of Page.xaml:

 public void Navigate(UIElement page)
        {
            //clear old page.
            spContent.Children.Clear();
            //add new page.
            spContent.Children.Add(page);
        }

Next I created a class called Pages.cs which holds the name and object type of each of our pages. Notice the difference between the HOME_PAGE property and the REGISTER and LOGIN properties. I realized early on that if I declared all of the page properties in the fashion of HOME_PAGE, it would create only one instance and then use that one from then on. The web is stateless but switching between pages in Silverlight is not if you use this method, so if you go to the Register page and fill out the form then go to another page and then back again to Register, you expect the form to be blank again but it won't be. The REGISTER and LOGIN properties will create new instances each time the page is requested to avoid this issue.

public class Pages
    {    
        //public pages.
        public static UserControl HOME_PAGE = new Home();
        public static UserControl REGISTER
        {
            get { return new Register(); }
        }
        public static UserControl LOGIN
        {
            get { return new Login(); }
        }
}

Next I created another class called Navigation.cs, which gives us a nice clean 1-liner way to navigate to a new page. The first thing you'll notice is BasePage, which will be set to the instance of our master page. This gives us a way to call the Navigate method in the master page from here so that in our pages we'll be able to call Navigation.Navigate(myPage); The alternative is referencing the App object, then referencing the master page (App.RootVisual), then calling Navigate from there (ugly!)

We have an overloaded Navigate method that lets us pass in a State object. This is just a way to pass a parameter to the next page you go to. A common use would be if you are on a business object list page and you're going to an edit business object page, you could pass the business object in here and then use it to populate the edit form in the edit page without having to hit the database again (very cool!)

The last thing you'll notice is that we're saving the name of the current page we're on in Isolated Storage, which you can think of as Silverlight's version of a cookie. It gets saved on the end-user's computer and gives us a way to persist the value if they exit our application. An important thing to remember here is that even hitting the browser's refresh will exit our application, which by default would bring them back to our default home page. By saving the page name, we can then bring the user back to the page they were on before they hit refresh.

using System.IO.IsolatedStorage;

public static class Navigation
    {
        //properties.
        public static Page BasePage { get; set; }
        public static object State { get; set; }

        public static void Navigate(UserControl page)
        {
            //erase state.
            State = null;
            //navigate.
            NavigateTo(page);
        }

        public static void Navigate(UserControl page, object state)
        {
            //save state to pass between pages.
            State = state;
            //navigate.
            NavigateTo(page);
        }

        private static void NavigateTo(UserControl page)
        {
            //save current page.
            SavePersistentValue("Current Page", page.ToString());
            //navigate.
            BasePage.Navigate(page);
        }

        #region Isolated Storage

        public static object GetPersistentValue(string key)
        {
            IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
            if (appSettings.Contains(key))
            {
                return appSettings[key] as object;
            }
            else
            {
                return null;
            }
        }

        public static void SavePersistentValue(string key, object value)
        {
            IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
            if (appSettings.Contains(key))
            {
                appSettings[key] = value;
            }
            else
            {
                appSettings.Add(key, value);
            }
        }

        #endregion

The last step is to handle the Application_Startup event in App.xaml.cs to set our Navigation.BasePage to our master page and then load up the current page we were on before the user exited the application.

private void Application_Startup(object sender, StartupEventArgs e)
        {
            //navigate to home page.
            this.RootVisual = new Page();
            Navigation.BasePage = this.RootVisual as Page;
            //check which page we were on.
            string pageName = Convert.ToString(Navigation.GetPersistentValue("Current Page"));
            if (pageName.Length > 0)
            {//navigate to current page.
                Type pageType = Type.GetType(pageName);
                UserControl currentPage = Activator.CreateInstance(pageType) as UserControl;
                Navigation.Navigate(currentPage);
            }
        }

And that's all folks... If you wanted to switch to the login page you would just do Navigation.Navigate(Pages.LOGIN), nice and clean...



Developing for Silverlight 2 and Silverlight 3

clock May 13, 2009 16:42 by author Justin Toth

I've been developing my personal website in Silverlight 3 beta as a way to learn the new features. However, today I needed to begin development on a website that will be going live fairly soon. As Silverlight 3 isn't projected to be released until maybe July or August (and it could very well be even later), I was forced to choose Silverlight 2. Unfortunately, you can't develop for Silverlight 2 and Silverlight 3 at the same time on the same box. As I'm opposed to using VM's these days after losing about a year of my life due to slow VM performance in the past, I searched google and was lucky enough to find this article:

http://blogs.msdn.com/amyd/archive/2009/03/18/switching-from-silverlight-3-tools-to-silverlight-2-tools.aspx

It gives you a nice .bat script that will automate most of the process of going between SL2 and SL3 so that you can easily switch between the 2 by clicking a few Next buttons and waiting 1-2 minutes. Problem solved!



Silverlight 3 ChildWindow Modal Popup

clock May 9, 2009 23:18 by author Justin Toth

Tonight I was looking at the Silverlight Toolkit Samples and found the ChildWindow control. This interested me because the first Silverlight tutorial I ever took was ScottGu's on building an application that can search for Digg articles, found here. When you click on an article in the listbox then a modal popup comes up containing more information. He achieved this modal popup functionality by creating a grey rectangle with some opacity that stretched across the screen horizontally and vertically. On top of that was a rounded border control with the content in there that would show up over the rectangle.

I used the concept from ScottGu's tutorial to create a page on my personal website that has a ListBox of some websites that I've created. When you click on one, the modal popup comes up showing more details of the work I did for that website. The ChildWindow control seemed a bit more polished to me so I decided to give it a go.

The first thing you need to do is make sure your project contains a reference to System.Windows.Controls. Interestingly, my application was a Silverlight Navigation project and already contained references to System.Windows.Controls and System.Windows.Controls.Navigation, which made me realize that the navigation functionality that I had been using must be a part of the Silverlight Toolkit! The next thing you'll want to do is add a control to your project for the modal popup. The cool thing here is that there is already a "Silverlight Child Window" control that you can add:

Here's what I did with my child window control, notice how I don't need to worry about the formatting of the window or the modal functionality, all I need to do is add my content that will go inside the modal popup.


<controls:ChildWindow x:Class="TothSolutions.SL.Controls.WorkPopup"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
           Width="600" Height="300"
           Title="WorkPopup">
    <Grid x:Name="LayoutRoot" Margin="10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
       
        <Image Source="{Binding ThumbNailBig}" Width="250" Margin="0,0,20,0" VerticalAlignment="Center" Grid.Column="0" Grid.Row="0" Grid.RowSpan="3" />
        <TextBlock Text="{Binding Title}" FontSize="20" Foreground="#000" FontWeight="Bold" Grid.Column="1" Grid.Row="0" />
        <HyperlinkButton Content="{Binding HrefLink}" TargetName="_new" NavigateUri="{Binding HrefLink}" FontSize="12" Margin="0,0,0,5" Grid.Column="1" Grid.Row="1" IsTabStop="False" />
        <TextBlock Text="{Binding FullDescription}" FontSize="12" Foreground="#000;" TextWrapping="Wrap" Grid.Column="1" Grid.Row="2" />
        <Button x:Name="CancelButton" Content="Close" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Center" Margin="0,12,0,0" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" />
    </Grid>
</controls:ChildWindow>

In the code-behind of the ChildWindow I wait until the control is loaded and then set the title of the modal popup based on the DataContext, which we'll pass in from the parent page. The title as well as a close button will show up at the top of the modal popup without us having to do anything more... Note: you could set the title in the constructor if it's a static value, e.g. this.Title = "My super cool modal popup!";

    public partial class WorkPopup : ChildWindow
    {
        public WorkPopup()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(WorkPopup_Loaded);
        }

        void WorkPopup_Loaded(object sender, RoutedEventArgs e)
        {
            Site site = DataContext as Site;
            this.Title = site.Title;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
    }

Lastly, on the parent page when the user clicks one of the items in my listbox, I create an instance of my ChildWindow, grab the business object for that row, set that business object as the DataContext of my ChildWindow, and lastly show the ChildWindow.

 private void SiteList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SiteList.SelectedItem != null)
            {
                Site site = SiteList.SelectedItem as Site;
                WorkPopup popup = new WorkPopup();
                popup.DataContext = site;
                popup.Show();
            }
        }

And that's it, easy peezie... Happy coding!!



Animating Page Transitions in Silverlight 3

clock May 8, 2009 10:31 by author Justin Toth

I wanted to add simple fade out/fade in animations to my page transitions in my Silverlight 3 app. I decided to tackle the fade in animation first, and my first attempt was to add a FadeIn storyboard to the LayoutRoot Grid of each of my pages like so:


        <Grid.Triggers>
            <EventTrigger RoutedEvent="Grid.Loaded">
                <BeginStoryboard>
                    <Storyboard x:Name="FadeIn">
                        <DoubleAnimation Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="Opacity"
                From="0" To="1" Duration="0:0:0.300"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Grid.Triggers>
 

You also have to add an Opacity of 0 to your LayoutRoot Grid. There are 2 issues with this approach. 1. You can't work in the designer anymore, as it's now set to invisible. 2. There is now duplicate xaml in every page, if you want to make changes to your animations than you'll have to do it in every single page.

My second attempt was to try and fade in/fade out the frame within MainPage.xaml. I set the frame's opacity to 0. The cool thing is that you can add storyboards to be invoked by code rather than attaching them to individual controls:


<UserControl.Resources>
  <Storyboard x:Name="FadeIn">
   <DoubleAnimation Storyboard.TargetName="Frame" Storyboard.TargetProperty="Opacity"
    From="0" To="1" Duration="0:0:0.200"/>
  </Storyboard>
  <Storyboard x:Name="FadeOut">
   <DoubleAnimation Storyboard.TargetName="Frame" Storyboard.TargetProperty="Opacity"
    From="1" To="0" Duration="0:0:0.200"/>
  </Storyboard>
 </UserControl.Resources> 

Next I had some work to do in the code-behind:

        private Button lnkMenu = null;

        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            this.FadeOut.Completed += new EventHandler(FadeOut_Completed);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            FadeIn.Begin();
        }

        private void NavButton_Click(object sender, RoutedEventArgs e)
        {
            lnkMenu = sender as Button;
            FadeOut.Begin();
        }

        void FadeOut_Completed(object sender, EventArgs e)
        {
            String page = lnkMenu.Tag.ToString();
            this.Frame.Navigate(new Uri(page, UriKind.Relative));
            FadeIn.Begin();
        }

Now we have all the page transition animation code in one place so we don't have to deal with the maintainability issue of having it in each page. Also the designers for every single page (including MainPage.xaml) will work now that we're not setting the opacity of any of the pages to 0.



Silverlight StackPanel + ListBox Issue

clock May 4, 2009 19:49 by author Justin Toth

Yesterday I was working on a Silverlight 3 beta application which didn't have fixed widths or heights, as I wanted the whole layout to expand and contract as the browser window did. For the layout I used StackPanels, as they seemed to be the most intuitive layout element due to their simple function - laying out items either horizontally or vertically.

Innocently, I created a ListBox that contained a TextBlock that was set to wrap. Unfortunately, the ListBox didn't respect its parent StackPanel container and the text extended off the right side of the page. My short-term hack was to hard-code in a width for the TextBlock but that meant that my ListBox didn't expand and contract as the page did.

I then created a large number of items in the ListBox and the bottom items disappeared off the bottom of the page. I knew that the ListBox internally contained a ScrollViewer so I was surprised why this wasn't invoked when it went off the page, again seeing the ListBox having no respect for its parent StackPanel container.

The solution was to replace the StackPanels that were parents of the ListBox with Grids and to set a property on the ListBox:

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">

This forced the ListBox to stay within the boundaries of the Grid and triggered the ListBox's internal vertical scrollbar to be invoked when it reached the bottom of the page. You can see an example of the listbox behaving itself here.



Introduction

clock May 3, 2009 19:30 by author Justin Toth

This is my first post and I'm excited to start blogging!! It seems like every day I run into some sort of issue and once I figure out how to solve it, it makes me wish I had a blog so I could post the solution so that others won't have to spend as much time on it as I did.

This blog will be related to .NET development, and more specifically front-end web development. I used to consider myself an ASP.NET developer but I feel like we've come upon a crossroads. Straight ahead is ASP.NET, to the left is pure javascript development, and to the right is Silverlight. You look further down the ASP.NET road and see that there's another branch up beyond this one, ASP.NET going to the left and ASP.NET MVC going to the right. Which road to take??



About the author

Justin

Justin is a senior developer who has been working with .NET since 2003. His main focus is building highly-interactive web applications using ASP.NET MVC and Dojo or jQuery. Visit his company's site at http://tothsolutions.com.

Page List

Sign in