Category Archives: Silverlight

Improving ListBox Performance in Silverlight for Windows Phone 7: Data Virtualization

There is a lot of data out there; on the the internet, tucked away in databases, sitting patiently on the other side of a REST web service just waiting to pounce on your unsuspecting Windows Phone application that just wants to display a little slice of it all so people can read it, touch it and generally make sense of it.  The problem is there is a lot of it, so what is a poor unsuspecting application to do, especially when it’s been crammed into a form factor that doesn’t allow ever expanding memory upgrades?

In this post and a few to come I’m going to explore the various ways you can work with the ListBox (the go-to control for displaying lists of data) in your application to keep it speedy and responsive.  Today we’re going to start with a feature added in Silverlight for Windows Phone: Data Virtualization.

Data Virtualization

Data virtualization is the concept of only loading “just enough” data to fill out your UI and be useful to interact with.  This is particularly useful if your data set is large and can’t all fit into memory at the same time.  Good examples are the 3,000 images you took of various pancakes shaped like childhood cartoon characters or all 23,083 remixes of The Postal Services “The District Sleeps Alone Tonight” you have loaded up on your phone.

Data virtualization in Silverlight is accomplished when you bind a custom IList implementation to a ListBox with a data template.  Let’s break that statement down by creating a very naïve virtualized list that simulates a list of 10,000 song objects.

Implement IList

This isn’t as daunting as it might seem, there are really only two methods you need to implement: Count and the indexer property.  Everything else can throw NotImplemented.  Count returns, well, the count of items while the indexer returns the actual item being requested by index.

Most of the magic happens in the indexer.  When an item is requested you now have a chance to go off and grab your data, fabricate it (such as using a WriteableBitmap), load it from IsolatedStorage, compute it based on index or generally return whatever makes sense.

Here I’m just creating a new Song class and setting its Title to a string that matches the requested index but in reality you’d be doing some parsing/loading/fetching here.

public class Song
{
    public string Title { get; set; }
    public string Length { get; set; }
}
public class VirtualSongList : IList<string>, IList
{
    /// <summary>
    /// Return the total number of items in your list.
    /// </summary>
    public int Count
    {
        get
        {
            return 10000;
        }
    }
    object IList.this[int index]
    {
        get
        {
            // here is where the magic happens, create/load your data on the fly.
            Debug.WriteLine("Requsted item " + index.ToString());
            return new Song() { Title = "Song " + index.ToString() };
        }
        set
        {
            throw new NotImplementedException();
        }
    }
    // everything else throws NotImplemented Exception.
    // .
    // .
    // .
}

NOTE: While the code is rather easy to implement it’s boring, mind numbingly boring so I’ve made the above implementation available for your source downloading pleasure.

Bind to ListBox

This is pretty straight-forward stuff, you’ll need to bind your new fancy list to the ListBox in question.

// Constructor
public MainPage()
{
    InitializeComponent();
    ItemList.ItemsSource = new VirtualSongList();
}

DataTemplate

One caveat is your ListBox needs to use a DataTemplate otherwise virtualization doesn’t kick in.  The virtualization code-path needs to make a few assumptions about your data and having a DataTemplate helps it down that path.  Without it all your hard work will go down the drain as the first time you bind your list every single item will be requested.

<ListBox x:Name="ItemList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Title}" FontSize="32" />
	</DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

In Action

Let’s take this code for a spin.  An F5 and emulator launch later and we’re looking at this pretty screen:

image

As you can see we’re using the Song created during the indexer call.  To prove it’s actually virtualized I added a Debug.WriteLine to output every time an item was requested:

image

As you can see only 52 items were requested instead of the full 10,000.  Why 52 instead of just 13?  You always want a few items as buffer to give your virtualizing code a chance to actually do the work while items are being scrolled into view.  For this reason we request about three page worth of data so your UI is always responsive.

Extending And Testing

A virtualized list that only returns 10,000 items is a bit limited.  A better, more testable pattern would be to create a separate repository or “creator” class that actually creates, counts and manages the objects.  Your list should be nothing but that, a list.

Caching

Another thing to be aware of, and this is important to pay attention to, virtualization doesn’t do any caching for you.  This means if you scroll down and then back up your virtualized list will ask for index 0 again and if you have a naïve implementation you will recreate item 0 over and over again.   Depending on what you’re returning you may want your repository to have some kind of object cache based on either time or current index.

When To Virtualize

If you attempt to do a lot in your indexer’s get, where you actually make the “virtual” data real, you’ll soon discover that your UI is now *worse* than it was before. That’s because as you’re scrolling it’s getting hit over and over again so if you have an expensive creation you’ll block your UI thread and everything will come to a screaming to a halt (some people say screeching halt but if I can’t interact with my UI you will hear screaming).

The general rule of thumb on when to use data virtualization is for large lists or medium lists whose items are heavy weight, such as images and expensive XAML objects.  The bottom line is you just can’t have all 3,000 images loaded up at once so you need some way to give the user a feeling of a nice, continuous smooth scroll.

So how do you minimize the delay from heavy weight objects?  Stay tuned for my next blog post when I talk about using proxy (some people like to say broker) objects to push as much of the real work into the background thread.

Getting Blur And DropShadow to work in the Windows Phone Emulator

I’ve noticed a few questions in the forums around why the Blur and DropShadow effects aren’t showing up in the Windows Phone 7 Series emulator and the simple answer is you have to set CacheMode to BitmapCache.

<TextBlock Text="DropShadow" Foreground="Black" FontSize="48" CacheMode="BitmapCache">
	<TextBlock.Effect>
		<DropShadowEffect/>
	</TextBlock.Effect>
</TextBlock>
<TextBlock Text="Blur" Foreground="Black" FontSize="48" CacheMode="BitmapCache">
	<TextBlock.Effect>
    	<BlurEffect/>
	</TextBlock.Effect>
</TextBlock>

We are working on setting this automatically so you don’t have to scratch your head each time you apply an effect and wonder why it looks fine on the design surface yet doesn’t show up in the emulator.

UPDATE [7/20/2011] – I was looking through my blog and realized this needs to be updated. For anyone still looking for this information all the effects such as Blur & DropShadow were intentionally disabled from the product for both 7.0 and the upcoming Mango.  The performance hit that applications took from using these effects put too much of a strain on the system and it was decided that if we couldn’t deliver a perfomant feature we would disable until such a time as we could.

Changing the Onscreen Keyboard (SIP) in Silverlight for Windows Phone 7 (WP7) using InputScope

Given that the main way users enter text in your Windows Phone 7 Series application is via a tiny onscreen keyboard (a “Software Input Panel” or SIP) it’s in everyone’s best interest to make sure the right keys are available to the user when they need them.

A good example is when you go to enter a PIN number you really only want to see number-related keys, when composing a SMS you’d like a quick way to insert an emoticon and if writing something longer you probably want auto-correction and replacement suggestions. The good news for Windows Phone developers is you can control which SIP layout is used and which auto-correct settings are enabled by setting the InputScope property of your TextBox.

The concept of InputScope isn’t new to XAML by the way, this concept already exists in WPF and was a nice fit with the native SIP behavior so if you’ve used InputScope before you should be right at home.

Setting InputScope

There are really three ways to set InputScope, two of which are cumbersome yet provide Intellisense and a third that is easy but requires you to know exactly which InputScope you’re after.

Via XAML

Doing it this way you’ll get full Intellisense yet it’s a lot of work to set a simple property:

<TextBox>
    <TextBox.InputScope>
        <InputScope>
            <InputScopeName NameValue="Text" />
        </InputScope>
    </TextBox.InputScope>
</TextBox>

Via Code

If you’re more the code-behind sort here it is in C#:

textBox1.InputScope = new InputScope()
{
    Names = { new InputScopeName() { NameValue = InputScopeNameValue.Text } }
};

Via XAML with a TypeConvertor

Remember how in high school they’d always teach you the hard way before showing you the easy version? Guilty as charged. If you already know the exact InputScopeNameValue you want to use, for example ‘Text’, then you can take advantage of the built-in TypeConvertor that is already wired up to the property and write this much easier XAML:

<TextBox InputScope="Text" />

InputScope Example Application

When we were bringing InputScopes from WPF to Silverlight for Windows Phone I wrote a quick app to show all the available InputScopes and automatically set the selected one on a TextBox. This gives you a feel for how many there are and what layout comes up when set. Here is what it looks like along with a link to the source:

Download the source.

InputScope Sample Application

Common InputScopes

Now that you know how to set them here are some of the more useful InputScopes:

Default

This is the default InputScope when no input scope is specified. Auto-capitalize first letter of sentence. The app can show app specific text suggestions.

Layout: Standard QWERTY layout.

Default InputScope
Number

When all you’re looking for is basic number entry. All features like auto-capitalize are turned off.

Layout: the first symbol page of the standard QWERTY layout.

Number InputScope
Text

When the user is typing standard text and can benefit from the full range of typing intelligence features:

  • Text suggestions (while typing and when tapping on a word)
  • Auto-correction
  • Auto-Apostrophe (English)
  • Auto-Accent
  • Auto-capitalize first letter of sentence

Layout: Text layout and access to letters, numbers, symbols and ASCII based emoticons + text suggestions.

Example fields: email subject and body, OneNote notes, appointment subject and notes, Word document, etc.

Text InputScope
Chat

The user is expected to type text using standard words as well as slang and abbreviations and can benefit from some of the typing intelligence features:

  • Text suggestions (while typing and when tapping on a word)
  • Auto-Apostrophe (English)
  • Auto-Accent
  • Auto-capitalize first letter of sentence

Layout: Chat layout and access to letters, numbers, symbols and rich MSN like emoticons + text suggestions.

Example fields: SMS, IM, Communicator, Twitter client, Facebook client, etc.

Chat InputScope
Url

The user is expected to type a URL. All auto-correct features are turned off.

Layout: Web layout with “.com” and “go” key

Url InputScope

For a complete list of InputScopes supported in Windows Phone 7 check out this MSDN link: InputScopeNameValue Enumeration.

In Conclusion

As you’re writing your applications don’t forget about InputScope, it’ll give it just that much more polish and can really make a difference in usability.

Slides + Code + Video from ‘An Introduction to Developing Applications for Microsoft Silverlight’ from MIX10

I promised someone at the end of my talk that I’d post my code and slides and while
I’m lagging a little behind I’ve finally bundled them up and made them available
for download here:

Slides + Code

Also, as a small note I’m slowly working this blog over to have a “Windows Phone
7 Design Series” look and feel, not sure how well the dark background and light
text is going to carry over or how well my design kung fu will stack up but here
goes.

UPDATE #1: I’m also including the actual session itself here for
your viewing pleasure.  You can either watch it below or
directly on the MIX website
.

UPDATE #2: Several people have asked me for sample code to the
solution that has a Windows Phone and Silverlight desktop application both consuming
the same Class Library.  Well, here it is for your downloading pleasure.

width="640" height="360">
Get Microsoft Silverlight

An Introduction to Developing Applications for Microsoft Silverlight @ MIX10

A quick heads up for anyone that saw my upcoming talk at MIX10. I’m super excited (why do normal excited when you can be *super* excited!) to show everyone the basics of Silverlight so people can begin creating rockstar web and Windows Phone applications. Speaking of the basics I want to share for anyone that did a Bing search wondering who this Shawn Oster fellow is and what his talk is really about.

My talk, An Introduction to Developing Applications for Microsoft Silverlight, really is an introduction, a 101. Maybe you are a HTML/JavaScript ninja, perhaps you’re just starting out, maybe you decided hand tuning assembly had lost its luster, whatever reason if you’re a blank Silverlight slate then this is the talk for you. On the other hand if you know about this crazy concept called XAML or have the basics of wiring up event handlers and doing a little data binding then this talk is definitely not for you.

If you’re hoping for some Windows Phone love then you don’t have to wait too much longer, Mike Harsh and Peter Torr lay down all the Windows Phone specific goods for you in the talks following mine. Think of my talk as a primer for those that need a quick intro to some of the concepts they’ll be seeing later.

MIX is an awesome, information-packed developer/designer lovefest and I’d hate for you to miss out on another track having to sit through 101 information.

Getting Excited for MIX10

MIX is by far my favorite Microsoft event, and not just because it’s in Las Vegas. It’s the mix of designers and developers, about learning cool stuff and just getting the creative juices flowing. Whether I’m there in person or just watching the keynote via the web it has a rejuvenating effect on me and gets me excited to make cool stuff.

This year I’m also excited for two reasons: first it looks like I’ll get to speak (link to my talk to be posted once it’s on the schedule) and two because as a gadget and code nerd we get to learn about the development story of the upcoming Windows Phone! Per the MIX website a few weeks back:

Yes, at MIX10 you’ll learn about developing applications and games for the next generation of Windows Phone. Yes, we’ll have Phone sessions, and we can’t say more…yet.

One thing I think people outside Microsoft don’t realize, at least I know I didn’t before working here, is that there is so much going on inside the company and we get so focused on whatever our project is that announcements like this are just as exciting for people inside the company as out!

Mix10_SeeYou_blk_240

Zune.net Now Using Silverlight 3.0

One criticism we get as a company is that on the day Silverlight 1.0 was launched we didn’t do a massive refactoring of all Microsoft media-based or media-containing sites to use Silverlight. Since dry humor doesn’t often translate via blog I’m poking some fun at our critics with that statement. Any technology transition takes time, even one we believe strongly in like Silverlight. Given skill sets, market requirements and different time-frames it was never that surprising that the previous Zune.net still used Flash. It just made sense at the time.

Today is a different story though, today we can count one more site as having come into the Silverlight fold, Zune.net. If you visit my Zune profile and do the right-click dance you’ll see the lovely “Silverlight” popup (circled in red below).

image

In fact Silverlight is used twice on the page, first as the portion that shows recent plays, badges and the artists a member is following as well as the media player on the bottom of the page.

image

That little player is pretty nice for playing 30-second previews but it’s even better when paired with a Zune Pass. If you’re logged in and you have a Zune Pass then you can stream the full length track of anything in the Zune catalog. You don’t even need the Zune client software installed to listen to full albums. To give iTunes a friendly little dig you have install the software just to search their catalog.

Two great tastes together at last Zune and Silverlight.

Silverlight TreeView Connecting Lines And Blend 3 Support for HierarchicalDataTemplates

The July 2009 release of the Silverlight Toolkit has a bunch of great things in it but a few of them require just a little digging. A common request in the forums and on CodePlex is how to add connecting lines to the standard TreeView. Well, thanks to TreeViewExtensions and a pre-built template it’s now an easy request to fulfill.

I’m going to show you how to add connecting lines using Blend 3 but it’s not a requirement. Grab a copy of Expression Studio 3 if you don’t already have Blend installed. There were a lot of great enhancements with the last release so I encourage you to give it a go.

Prerequisites

  1. Make sure you’ve installed the July 2009 release of the Silverlight Toolkit
  2. Start a new Silverlight project in Blend 3
  3. While you could start by dragging a TreeView from the Asset pane onto the design surface I want to show off Blend’s support for sample data and editing the HierarchialDataTemplate.

Define Sample Data

One of the more annoying things when trying a do a little research into how you can tweak a control is having to come up with some kind of mock data to work with, especially when working with a TreeView because of its hierarchical nature. Blend 3 introduced a huge time-saving feature, Sample Data, that we’ll take advantage of.

For this example I want to end up with a common TreeView UI pattern, an icon followed by some text, similar to a basic file browser. With those requirements in mind lets create some sample data.

  1. Switch to the Data panel
  2. Click on the ‘Add sample data source’ icon (circled below) and choose ‘Define New Sample Data…’
    Define New Sample Data
  3. Go with all the defaults and click OK
  4. Presto, magic sample data!

At this point you can drag the SampleDataSource onto the design surface and Blend will create a ListBox with fields properly bound to the control and fully interactive sample data. Very useful but we need to do a just a little more tweaking to get it where we want it.

Change the property type of Property1 to an Image and Property2 to a String. You do this via the property type dialog accessed by clicking on the icon to the right of property name (circled below).

image

Almost there. We now have an image and some text but it’s missing that hierarchical nature. Easy enough to fix. Click on the drop down to the right of the Collection and click “Convert to Hierarchical Collection”:

image

At this point you’ll have a collection that contains a collection that contains a collection that… you get my drift. Grab the first Collection underneath SampleDataSource and drag it onto the Blend design surface and watch the magic happen!

You’ll end up with something like this:

image

Pretty awesome considering you didn’t have to create a single mock object, mess with any XAML or write any code.

Customizing the HierarchialDataTemplate in Blend

OK, now that the rush of excitement has worn off (if it hasn’t don’t worry, just take a few deep breaths, take a walk and come back when you’ve got your heart rate under control) the harsh reality creeps in that this doesn’t look exactly like your basic file browser. Image is a bit big and the text is underneath it the icon.

Easy enough to fix:

  1. Select the TreeView
  2. There are at least three ways to navigate to the Edit Current Template menu but I find the fastest is clicking on the TreeView breadcrumb underneath the MainPage.xaml tab (illustrated below)
    image

At this point you have a very simple template to work with, a basic StackPanel containing an Image and TextBlock

image

Go ahead and tweak the template into something a little more like what you’d expect from a file browser:

  1. Change the orientation of the StackPanel to Horizontal
  2. Change the Width and Height of the Image to 16 x 16
  3. Change the VerticalAlignment of the TextBlock to Center

Now we have something much more useful:

image

(I changed my sample data generation on the string to only create one word with a maximum of 12 characters)

Where Are Those Connecting Lines?

I know what you’re thinking, I brought you all this way, are we ever going to get to the connecting lines part? Well, the grand revel is here!

  1. Add a reference to System.Windows.Controls.Toolkit (if you went with the default install it should be in C:Program FilesMicrosoft SDKsSilverlightv3.0ToolkitJul09Bin)
  2. Download TreeViewConnectingLines.xaml and add it to your project
  3. Switch to the Resources panel and expand TreeViewConnectingLines.xaml, it’ll look like this:
    image
  4. There is a style for both the TreeView itself and the TreeViewItems that it contains.
  5. Drag ConnectingLinesTreeView onto the TreeView and when prompted select “Select property on “[TreeView]” Style
    image
  6. Switch to the Properties panel for the TreeView
  7. Scroll down to ItemContainerStyle (in Miscellaneous section)
  8. Click the Advanced property button to the right of the property (circled below)
    image
  9. Select Local Resource –> ConnectingLinesTreeViewItem

And there you go! You now have connecting lines, with a plus/plus icon showing expansion state. It even shows inside of Blend so you see exactly what you get but it’s more fun to run it and see it in all its connecting line glory!

image

Source

UPDATE: I’ve been asked in the comments to provide the source so without further ado get it here:

Connecting Lines Source

Epilogue

To be honest I could have just started with adding the connecting lines and you’d be on your way but I really wanted to show off sample data for TreeView, converting that sample data into a hierarchy and editing the HierarchicalDataTemplate in Blend 3.

MIX ‘09 & The Silverlight Toolkit March 2009 Release

It has been an action packed last week, a lot getting announced, released and talked about. What happened?

MIX ‘09

MIX09 was awesome, first because it was the first one I’ve ever been able to attend and second because of all the great announcements and energy of the people. I met great people, had amazing conversations and the energy was so high that I didn’t even notice that I lived off of Red Bull and a couple of hours a sleep a night.

No, the Adobe guy and I didn’t fight as people kept asking me :). We had a great conversation though I do forget his name (drop me a line if you read this cool Adobe guy). That’s in fact one of the reasons I love MIX, it’s bringing together different people inside the industry all focused on making rich interactive experiences for the web denizens. It’s saying here are all these cool tools and technologies but instead of focusing on whether a site is Rails or ASP.NET MVC lets talk about how to give users something useful.

I was asked a great question by my sound guy (thanks for making me sound good!) after my talk:

“As a consumer, as someone that uses the web, why should I care about Silverlight?”

A lot of reasons went through my head and I tried to imagine what a good marketing peep would say but perhaps due to the lack of sleep I instead spoke the first thing that came to my mind which is that “You shouldn’t care about Silverlight, you should care about the great applications these people are creating with it.” That really goes for any technology, at the end of the day people don’t care about Flash or Silverlight or whether your site is 100,000 lines of spaghetti code being spit out by CGI scripts, they just want it to work easily without getting in their way while providing a rockstar experience.

I talked with people from all over the industry, from companies that are often our competition but at the end of the day we all want to provide a killer experience for the people that just want to watch a little bit of March Madness online :) See what I did there, I just made someone in marketing happy but I’m also highlighting that the web is about providing an experience, not what technology is used. You can watch March Madness in SD using the Flash player or in HD with Silverlight. By the way if you haven’t watched a game in HD in your browser I encourage you to do so, it’s awesome. I don’t even really like basketball but I find myself watching it amazed at the quality that’s being live streamed.

Silverlight Toolkit March 2009

To coincide with MIX we released a new version of the toolkit, officially known as the Silverlight Toolkit March 2009 release. As a team that focuses on bringing new controls to everyone this release initially felt ‘light’, because with every release we want to bring as many controls as possible and to fix every bug under the sun but as I was preparing for my MIX talk we realized there is a ton of stuff in this release. It was a true forest for the trees moment. You can find all the goods in the official release notes but here are just a few highlights:

  • New Controls: Accordion, DomainUpDown, TimeUpDown, TimePicker, LayoutTransformer, TransitioningContentControl, AreaSeries (for charting). Check out the DomainUpDown sample showcasing Jesse Liberties tutorial videos. Pure hotness.
  • Silverlight 3 Beta Controls: DataPager, ChildWindow, Frame/Page, DataForm, Validation controls (ErrorSummary, FieldLabel, DescriptionViewer) and DataGrid enhancements.
  • Bug fixes as always.
  • VB.NET versions of all the samples! The community spoke and we listened so now we have full VB.NET samples.
  • A real installer that puts the controls right into the Visual Studio and Blend toolbox. The less monkey work you have to do to get off the ground with the controls the better.
  • New source! Now the full source for Calendar, DatePicker, GridSplitter and TabControl are in the toolkit. No more needing crack those open using Reflector, you can go straight to the source, comments and all.

High-Speed RIA Development Talk

If you were at my talk at MIX and had a question I left you hanging with ask it in the comments or forums, we’ll get your questions answered. Also any feedback you want to give would be great. I have a thick skin, I can take it :) I want to make sure that my next talks address your needs better and also to help shape future blog posts about what things you may want to hear about and see.

My MIX Talk Online

Update: If you want to tease, scoff or hear about what’s new in the Silverlight Toolkit you can watch my session online. If you want to learn more about sharing skills and code between Silverlight & WPF check out my team mates Jeff Wilcox’s talk.

MVP Summit Talk: Silverlight Toolkit: Past, Present & Future

Today I’m giving a talk at Microsoft’s 2009 MVP Global Summit here on campus. The title of the talk is “Silverlight Toolkit: Past, Present & Future” and I’ll be talking a little bit about where the Silverlight Toolkit came from, what’s going on with it right now and what we’re planning in future versions. Pretty self-explanatory actually :) I’m done a few dry-runs and once it came out at 30 minutes, the next at an hour and 15 minutes so I’m hoping I’ll find a nice average and nail the 45 minute window I have.

We’ve done a lot with the toolkit in a very short time and we’re not done yet. There are some really great things shipping in the MIX09 time-frame and I’m lucky enough to get to speak about them at MIX09 as well.

For anyone coming to my talk today I look forward to sharing our plans with you and if you were there feel free to drop me a line with any follow up questions.