The blog of dlaa.me

Posts from March 2008

Improved access to Silverlight 2's generic.xaml resources [SilverlightDefaultStyleBrowser available via ClickOnce]

In response to my previous post announcing the SilverlightDefaultStyleBrowser tool for working with default styles for Silverlight 2 controls, I got an email from Rob Relyea suggesting that I make SilverlightDefaultStyleBrowser available via ClickOnce as well. (For those who may not be familiar with it, here's a brief ClickOnce overview.) ClickOnce is simple to configure, adds a Start Menu entry automatically, supports seamlessly updating an application, and installs/uninstalls on Vista as standard user without requiring elevation - so this was easy to do!

SilverlightDefaultStyleBrowser sample image

[Click here or on the image above to install SilverlightDefaultStyleBrowser with ClickOnce.]

The functionality of SilverlightDefaultStyleBrowser is the same whether you use the executable in the ZIP or use the ClickOnce version - so pick whatever suits you best. And have fun styling those controls! :)

Note: The source code for SilverlightDefaultStyleBrowser is available only in the ZIP file download.

Improving everyone's access to Silverlight 2's generic.xaml resources [SilverlightDefaultStyleBrowser tool and source code]

When customizing the look and feel of a Silverlight 2 control, people usually want to start with a copy of the control's default visuals. Unfortunately, getting at the default XAML for a control isn't always obvious or easy. A control's default XAML is stored in a specially named resource of the control's assembly and that resource (named generic.xaml) isn't particularly easy to get at by default. The good news is that the controls in the Silverlight 2 Beta 1 SDK/Tools are documented on MSDN and that documentation includes the default styles.

But sometimes I prefer something a little "closer to the metal", so I wrote a small WPF 3.5 application to improve this experience for developers and designers working with Silverlight 2 controls. SilverlightDefaultStyleBrowser is a simple application that automatically extracts the default styles from an assembly's generic.xaml, lists the available control styles, and presents them in an easy-to-browse manner with syntax highlighting, automatic formatting, and expandable/collapsible nodes. The common scenario of copying a Style or Template is made easy by two dedicated buttons that do just that!

SilverlightDefaultStyleBrowser sample image

[Click here or on the image above to download a ZIP of the SilverlightDefaultStyleBrowser tool - and its complete WPF 3.5 source code.]

Using SilverlightDefaultStyleBrowser is deliberately simple. When the application loads, it automatically looks in the Silverlight SDK default install directory, parses all the assemblies it finds there, and adds the relevant styles to its list (as seen in the image above). Adding additional assemblies is as easy as hitting the "Add Assembly" button, selecting the assemblies, and hitting OK. Once the styles are loaded, simply select the control of interest to browse its default XAML. The "Copy Style to Clipboard" button copies the XAML for the entire style to the clipboard. The "Copy Template to Clipboard" button copies just the template XAML from within the Style (probably the more common scenario). Paste the copied XAML directly into your Silverlight application, tweak it or customize it, and you're set - it's that easy!

Notes:

  • SilverlightDefaultStyleBrowser tries to make things as easy as possible, but sometimes it's still necessary to edit the generated XAML a bit to get it to compile. Usually, this is because the XAML is referencing a non-default namespace that didn't get copied over because it wasn't directly part of the XAML (ex: the "local:" prefix in a TargetType attribute). In these cases, it's necessary to add the xmlns mapping manually. However, the default behavior of SilverlightDefaultStyleBrowser should provide a simple paste-and-go experience in most cases.
  • If you paste some XAML and then get the compile error "An item with the same key has already been added.", it's probably because you checked the "Namespaces" CheckBox. Doing so turns off SilverlightDefaultStyleBrowser's default behavior of removing the default "xmlns" and "xmlns:x" declarations from the XAML it provides (to avoid this very compile error). If you changed that setting because you wanted the pure, untouched XAML, then it's your job to remove the redundant namespaces - otherwise just uncheck the CheckBox and hit the "Copy" button again. :)
  • WatermarkedTextBox in the System.Windows.Controls.Extended assembly is not listed because that control uses its own private XAML resource instead of generic.xaml. You'll need to refer to the documentation if you want that control's default XAML.
  • The mysterious entry for "Control" actually applies to the GridSplitter control from the System.Windows.Controls.Extended assembly which is using a non-standard mechanism to store this style.
  • The templates for Silverlight 2 Beta 1 controls that are not part of the SDK (ex: TextBox, ItemsControl) are not stored in generic.xaml form and are therefore unavailable to SilverlightDefaultStyleBrowser even if you add all the assemblies in the Silverlight install directory.

Silverlight and WPF are all about allowing developers and designers to easily customize the look and feel of their applications. I hope SilverlightDefaultStyleBrowser helps make that process even easier for both groups!

Code to support new features doesn't write itself [HtmlTextBlock sample gets data binding support!]

In the comments to my post about porting the HtmlTextBlock sample to Silverlight 2 Beta 1, kind reader eibrahim pointed out that Silverlight 2's data binding feature wasn't working with HtmlTextBlock. I explained why in a reply to that comment:

This is a consequence of me doing as simple a port as possible. :( Recall that Silverlight 1.1 Alpha did not support data binding, so this issue simply couldn't exist there. Now that Silverlight 2 Beta 1 supports data binding, HtmlTextBlock needs a minor change to support it. In particular, its properties need to be backed by DependencyProperties in order for data binding to work as we'd like. I'll be updating the sample soon to add this support ...

I've just finished updating the code to back each of the settable HtmlTextBlock properties that mirror TextBlock properties with a DependencyProperty in order to enable data binding and maintain HtmlTextBlock as "plug-compatible" with TextBlock as possible. Most of this was pretty straightforward (boring) typing, so I'll confess that I have not tested each property individually. :| But I did create a simple project (attached to this post) demonstrating HtmlTextBlock data binding - both standalone and within a ListBox DataTemplate - that interested readers can use to play around with this. I've also updated the HtmlTextBlock.cs file in the existing HtmlTextBlock source code download.

Thanks for the feedback, eibrahim, I hope you and others find that the new data binding support works well and enables even more compelling scenarios!

[HtmlTextBlockAndDataBinding.zip]

Continuing support for simple HTML display in Silverlight [HtmlTextBlock sample updated for Silverlight 2 Beta 1!]

A few months ago when Silverlight 1.1 Alpha was all the rage, I wrote a sample control that made a best-effort attempt to display simple HTML markup in Silverlight. The original HtmlTextBlock post described the control's purpose and the follow-up post detailed a number of improvements to HtmlTextBlock. (Please continue to refer to those posts for background and implementation details.) Now that Silverlight 2 Beta 1 is released, I've had a few internal and external requests to modify HtmlTextBlock to work with the latest Silverlight bits.

HtmlTextBlock Demonstration

I've updated the original HtmlTextBlock demonstration page and also updated the original source code download, so don't hesitate to try things out in your own browser and/or download the code to see how it works!

Notes:

  • There were no fundamental changes to the features HtmlTextBlock uses, so the port from 1.1 Alpha to 2 Beta 1 was straightforward.
  • Thanks to Silverlight 2's flexible layout system, the code to override Width/Height/ActualWidth/ActualHeight and handle the Loaded event is all now unnecessary and has been removed.
  • The XAML passed to Control.InitializeFromXaml now specifies the default XML namespace.
  • Silverlight 2 Beta 1's TextBlock exposes the new properties LineHeight, LineStackingStrategy, and TextAlignment which HtmlTextBlock mirrors.
  • A handful of properties/classes changed names/types slightly.
  • The syntax for creating an instance of the Silverlight control in HTML has changed to use the <OBJECT> tag.

Curiously, certain text/style/size combinations don't seem to render under Silverlight 2 Beta 1. For example, viewing the initial sample text at Verdana/8, Lucida Sans Unicode/10, or Times New Roman/10 shows an empty box. Because changing the font face/size doesn't actually change the Silverlight object tree that HtmlTextBlock creates, I'm inclined to believe this is a rendering issue with the Silverlight Beta rather than a bug in HtmlTextBlock. However, if anyone finds otherwise, please let me know!

It's always great to hear that people have found value in the stuff I've posted to my blog. I hope that those of you who are using HtmlTextBlock continue using it successfully with Silverlight 2 Beta 1 - and that newcomers find something useful as well!

Blogging code samples should be easy [Free ConvertClipboardRtfToHtmlText tool and source code!]

I've been including a lot of source code examples in my blog lately and needed a good way to paste properly formatted code in blog posts. I write my posts in HTML and wanted a tool that was easy to use, simple to install, produced concise HTML, and worked well with Visual Studio 2008. I was aware of a handful of tools for this purpose but none of them were quite what I was looking for, so I wrote my own one evening. :)

Caveat: ConvertClipboardRtfToHtmlText is a simple utility written for my specific scenario. I'm releasing the tool and code here in case anyone wants to use it, enhance it, or whatever. I have NOT attempted to write a solid, general-purpose RTF-to-HTML converter. Instead, ConvertClipboardRtfToHtmlText assumes its input is in the exact format used by Visual Studio 2008 (and probably VS 2005).

Using ConvertClipboardRtfToHtmlText is simple:

  1. Copy code (C#, XAML, etc.) to clipboard from Visual Studio 2008
  2. Run ConvertClipboardRtfToHtmlText to convert the RTF representation of the code on the clipboard to HTML as text (there's no UI because the tool does the conversion and immediately exits)
  3. Paste the HTML code on the clipboard into your blog post, web page, etc.

I'm the first to acknowledge there's a lot of room for improvement in step #2. :) While the current implementation is good enough for my purposes, I encourage interested parties to consider turning this into a real application - maybe with a notify icon and a system-wide hotkey. If you do so, please let me know because I'd love to check it out!

The compiled tool and code are available in a ZIP file attached to this post. The complete source code is also available below. Naturally, I used ConvertClipboardRtfToHtmlText to post its own source code. :)

Enjoy!

Updated 2008-04-02: Minor changes to code and tool

 

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

// Convert Visual Studio 2008 RTF clipboard format into HTML by replacing the
// clipboard contents with its HTML representation in text format suitable for
// pasting into a web page or blog.
// USE: Copy to clipboard in VS, run this app (no UI), paste converted text
// NOTE: This is NOT a general-purpose RTF-to-HTML converter! It works well
// enough on the simple input I've tried, but may break for other input.
// TODO: Convert into a real application with a notify icon and hotkey.
namespace ConvertClipboardRtfToHtmlText
{
    static class ConvertClipboardRtfToHtmlText
    {
        private const string colorTbl = "\\colortbl;\r\n";
        private const string colorFieldTag = "cf";
        private const string tabExpansion = "    ";

        [STAThread]
        static void Main()
        {
            if (Clipboard.ContainsText(TextDataFormat.Rtf))
            {
                // Create color table, populate with default color
                List<Color> colors = new List<Color>();
                Color defaultColor = Color.FromArgb(0, 0, 0);
                colors.Add(defaultColor);

                // Get RTF
                string rtf = Clipboard.GetText(TextDataFormat.Rtf);

                // Parse color table
                int i = rtf.IndexOf(colorTbl);
                if (-1 != i)
                {
                    i += colorTbl.Length;
                    while ((i < rtf.Length) && ('}' != rtf[i]))
                    {
                        // Add color to color table
                        SkipExpectedText(rtf, ref i, "\\red");
                        byte red = (byte)ParseNumericField(rtf, ref i);
                        SkipExpectedText(rtf, ref i, "\\green");
                        byte green = (byte)ParseNumericField(rtf, ref i);
                        SkipExpectedText(rtf, ref i, "\\blue");
                        byte blue = (byte)ParseNumericField(rtf, ref i);
                        colors.Add(Color.FromArgb(red, green, blue));
                        SkipExpectedText(rtf, ref i, ";");
                    }
                }
                else
                {
                    throw new NotSupportedException("Missing/unknown colorTbl.");
                }

                // Find start of text and parse
                i = rtf.IndexOf("\\fs");
                if (-1 != i)
                {
                    // Skip font size tag
                    while ((i < rtf.Length) && (' ' != rtf[i]))
                    {
                        i++;
                    }
                    i++;

                    // Begin building HTML text
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("<pre><span style='color:#{0:x2}{1:x2}{2:x2}'>",
                        defaultColor.R, defaultColor.G, defaultColor.B);
                    while (i < rtf.Length)
                    {
                        if ('\\' == rtf[i])
                        {
                            // Parse escape code
                            i++;
                            if ((i < rtf.Length) &&
                                (('{' == rtf[i]) || ('}' == rtf[i]) || ('\\' == rtf[i])))
                            {
                                // Escaped '{' or '}' or '\'
                                sb.Append(rtf[i]);
                            }
                            else
                            {
                                // Parse tag
                                int tagEnd = rtf.IndexOf(' ', i);
                                if (-1 != tagEnd)
                                {
                                    if (rtf.Substring(i, tagEnd - i).StartsWith(colorFieldTag))
                                    {
                                        // Parse color field tag
                                        i += colorFieldTag.Length;
                                        int colorIndex = ParseNumericField(rtf, ref i);
                                        if ((colorIndex < 0) || (colors.Count <= colorIndex))
                                        {
                                            throw new NotSupportedException("Bad color index.");
                                        }

                                        // Change to new color
                                        sb.AppendFormat(
                                            "</span><span style='color:#{0:x2}{1:x2}{2:x2}'>",
                                            colors[colorIndex].R, colors[colorIndex].G,
                                            colors[colorIndex].B);
                                    }
                                    else if("tab" == rtf.Substring(i, tagEnd-i))
                                    {
                                        sb.Append(tabExpansion);
                                    }

                                    // Skip tag
                                    i = tagEnd;
                                }
                                else
                                {
                                    throw new NotSupportedException("Malformed tag.");
                                }
                            }
                        }
                        else if ('}' == rtf[i])
                        {
                            // Terminal curly; done
                            break;
                        }
                        else
                        {
                            // Normal character; HTML-escape '<', '>', and '&'
                            switch (rtf[i])
                            {
                                case '<':
                                    sb.Append("&lt;");
                                    break;
                                case '>':
                                    sb.Append("&gt;");
                                    break;
                                case '&':
                                    sb.Append("&amp;");
                                    break;
                                default:
                                    sb.Append(rtf[i]);
                                    break;
                            }
                        }
                        i++;
                    }

                    // Finish building HTML text
                    sb.Append("</span></pre>");

                    // Update the clipboard text
                    Clipboard.SetText(sb.ToString());
                }
                else
                {
                    throw new NotSupportedException("Missing text section.");
                }
            }
        }

        // Skip the specified text
        private static void SkipExpectedText(string s, ref int i, string text)
        {
            foreach (char c in text)
            {
                if ((s.Length <= i) || (c != s[i]))
                {
                    throw new NotSupportedException("Expected text missing.");
                }
                i++;
            }
        }

        // Parse a numeric field
        private static int ParseNumericField(string s, ref int i)
        {
            int value = 0;
            while ((i < s.Length) && char.IsDigit(s[i]))
            {
                value *= 10;
                value += s[i] - '0';
                i++;
            }
            return value;
        }
    }
}

[ConvertClipboardRtfToHtmlText.zip]

LB-SV-WHY [Three wacky uses for Silverlight 2's ListBox and ScrollViewer!]

In my Silverlight 2 ListBox/ScrollViewer FAQ I described some common scenarios and demonstrated how to implement them with sample XAML/code. In this post I demonstrate three UNcommon ListBox/ScrollViewer scenarios - again showing the XAML/code that makes them possible.

Because sometimes the power of a thing only becomes clear when it's being abused. :)

 

ListBox: Planets

When I saw Beatriz Costa's "PlanetsListBox" WPF demo of a fully functioning ListBox that looked like the solar system, I was stunned and knew I had to port it to Silverlight.

Planets shown smaller than actual size

So I downloaded the WPF project, created a new Silverlight application, copied over the implementations of the classes SolarSystem, SolarSystemObject, and ConvertOrbit, and went to work migrating the XAML. With one small exception, the code had no changes for Silverlight. As you'd expect, the XAML got a variety of minor tweaks because Silverlight is a subset of WPF and I was moving in the "wrong" direction. In particular, I made the following changes to the original implementation:

  • Switched to inline styles because Silverlight does not support implicit styles
  • Switched from a Trigger-based selection indicator (the yellow circle) to one based on the Silverlight parts model
  • Manually created Canvas bindings in PrepareContainerForItemOverride because Silverlight wasn't creating the attached property bindings in XAML
  • Manually created ToolTip contents/bindings in a custom IValueConverter because bindings in the ToolTip XAML were unexpectedly seeing a null DataContext
  • Changed the type of SolarSystemObject.Image from Uri to string and changed the image resource paths so that binding to Silverlight's Image.Source worked
  • Switched to Canvas.Top because Silverlight does not support Canvas.Bottom
  • Converted all images to JPEG format because GIF is not supported by Silverlight

 

ListBox: Slideshow

One day I was working on a perfectly sensible ListBox sample with images when my teammate Ted suggested making a simple Slideshow with ListBox. It's not the craziest idea he's ever had, so I decided to humor him.

It's not much of a list anymore...

The basic idea is simple: Populate the ListBox with images and then size it so only one of them shows at a time. You can use the dedicated Previous/Next Buttons to change slides - or click on the ListBox and press the usual keys (arrow Up/Down, Home/End, Page Up/Down). Because the Button states are updated in the SelectionChanged handler, they're kept in sync. Here's the complete implementation:

<UserControl x:Class="ListBoxSlideShow.Page"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls">
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">

        <!-- Column/row definitions -->
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <!-- ListBox slide display -->
        <ListBox
            x:Name="Display" Grid.ColumnSpan="2" Width="484" Height="364"
            controls:ScrollViewer.HorizontalScrollBarVisibility="Hidden"
            controls:ScrollViewer.VerticalScrollBarVisibility="Hidden">

            <!-- Style to size all images to desired size -->
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="Width" Value="480"/>
                    <Setter Property="Height" Value="360"/>
                </Style>
            </ListBox.ItemContainerStyle>

            <!-- Slide images -->
            <!-- Note: Sample images are from C:\Windows\Web\Wallpaper\*
                       Update that path if necessary for your machine -->
            <Image Source="img10.jpg"/>
            <Image Source="img7.jpg"/>
            <Image Source="img8.jpg"/>
            <Image Source="img9.jpg"/>
        </ListBox>

        <!-- Previous/Next buttons -->
        <Button x:Name="Previous" Grid.Column="0" Grid.Row="1" Content="Previous"/>
        <Button x:Name="Next" Grid.Column="1" Grid.Row="1" Content="Next"/>
    </Grid>
</UserControl>
using System;
using System.Windows.Controls;

namespace ListBoxSlideShow
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            // Hook button event handlers to change slides
            Previous.Click += delegate { ChangeSlide(Display.SelectedIndex - 1); };
            Next.Click += delegate { ChangeSlide(Display.SelectedIndex + 1); };

            // Update button states if necessary
            Display.SelectionChanged += delegate
            {
                Previous.IsEnabled = (0 < Display.SelectedIndex);
                Next.IsEnabled = (Display.SelectedIndex < Display.Items.Count - 1);
            };

            // Change to first slide
            ChangeSlide(0);
        }

        private void ChangeSlide(int index)
        {
            // Select specified slide and bring it into view
            Display.SelectedIndex = Math.Max(0, Math.Min(Display.Items.Count - 1, index));
            Display.ScrollIntoView(Display.SelectedItem);
        }
    }
}

 

ScrollViewer: Marquee

On a discussion list one day, someone innocently asked for a way to scroll text. I immediately thought: <MARQUEE>!

Welcome back to Web 1.0!

Again, the idea is simple: Put arbitrary content inside a ScrollViewer, hide its ScrollBars, and adjust its HorizontalOffset on a timer. I chose to have the content bounce at each end, but you could just as easily snap it back to the beginning. Here's the complete implementation:

<UserControl x:Class="ScrollViewerMarquee.Page"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>

        <!-- Marquee-like ScrollViewer -->
        <ScrollViewer x:Name="Marquee" Width="200"
                      VerticalAlignment="Center"
                      HorizontalScrollBarVisibility="Hidden"
                      VerticalScrollBarVisibility="Disabled">

            <!-- Arbitrary nested content -->
            <TextBlock Text=" This message bounces! "
                       FontFamily="Arial Black" FontSize="40"/>
        </ScrollViewer>
    </Grid>
</UserControl>
using System;
using System.Windows.Controls;
using System.Windows.Threading;

namespace ScrollViewerMarquee
{
    public partial class Page : UserControl
    {
        // Timer and direction variables
        private DispatcherTimer _timer;
        private int _delta = 1;

        public Page()
        {
            InitializeComponent();

            // Create timer to tick every 10ms
            _timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(10)
            };

            // Attach a Tick handler to do the scrolling
            _timer.Tick += delegate
            {
                // Adjust the horizontal offset
                Marquee.ScrollToHorizontalOffset(Marquee.HorizontalOffset + _delta);

                // Flip direction if necessary
                if ((0 < Marquee.ViewportWidth) &&  // (NOOP if not visible yet)
                    ((Marquee.ScrollableWidth <= Marquee.HorizontalOffset) ||
                     (Marquee.HorizontalOffset <= 0)))
                {
                    _delta = -_delta;
                }
            };

            // Start the timer
            _timer.Start();
        }
    }
}

 

I've made the complete source code I used to build these samples available as an attachment to this post for anyone to play around with. If you come up with your own wacky use for ListBox or ScrollViewer, please let me know. It's always interesting to see the clever, creative ways people end up using stuff like this!

[LB-SV-WHY.zip]

LB-SV-WPF [Silverlight 2's ListBox and ScrollViewer controls running on WPF!]

In the Silverlight 2 ListBox/ScrollViewer FAQ, I mentioned that I'd done a lot of Silverlight control development on WPF. I spoke with a number of people at MIX08 last week and many of you wanted to know more. So I've created a Visual Studio solution with one project to compile these Silverlight controls on WPF and another project to run the corresponding unit tests. I've also implemented a simple demonstration of the WPF ListBox/ScrollViewer running side-by-side with the Silverlight ListBox/ScrollViewer (all on WPF):

Silverlight 2's ListBox and ScrollViewer running on WPF

While there are some obvious style differences between the default look and feel of the two platforms, the control functionality is very similar. To prove it, I've attached a ZIP of the solution to this blog post so you can run the demo application on your own machine. [Aside: I did not say the behavior was identical, just very similar. :) ]

And though I didn't enable code coverage by default, those of you with the Visual Studio Code Coverage feature installed can easily turn it on by editing the LocalTestRun.testrunconfig settings. When compiled for WPF, ListBox and ScrollViewer live in the WPF namespace to avoid colliding with WPF's classes in System.Windows.Controls. So we can see below that the overall coverage for these controls is a smidge under 80% (the uncovered code is mostly involved with user interface manipulation (ex: mouse and key input) which I wasn't able to flush out because I ran out of time):

Code coverage for the ListBox and ScrollViewer unit tests

So if you were wondering whether it was possible to easily share code, XAML, and unit tests across both Silverlight and WPF, the answer is a definite YES! :)

 

Notes:

  • In this case, the code for ListBox, ListBoxItem, ScrollViewer, and ScrollContentPresenter is taken from Silverlight, but the underlying implementations of ItemsControl, ContentPresenter, and ScrollBar are provided by WPF. (So some behavior differences in the dependent controls are reflected by ListBox/ScrollViewer.)
  • I wanted to make as few changes as possible when creating this sample - here's a summary of what I did:
    • Created a new WPF project.
    • Copied all code files directly from the public Silverlight 2 Beta 1 controls source code download.
    • Copied default styles from the associated generic.xaml file to the new project's Window1.xaml as implicit styles for the Silverlight control implementations.
    • Removed TemplateBindings from ContentPresenter/ScrollContentPresenter because they're not necessary on WPF (the ContentControl-ContentPresenter hook-up is done automatically) and removed Setters for related properties.
    • Added Animations to ListBoxItem's "Normal State" because the "restore default settings" behavior that's core to Silverlight's parts model specification is not present on WPF.
    • Added a few calls to Math.Round to ListBox's IsOnCurrentPage method. (I deliberately avoided duplicating WPF's MS.Internal.Double.Util.* helper methods for the Silverlight ListBox and have seen no problems because of that. However, when running the sample on WPF, I found a few situations where the double rounding issues were causing problems, so I patched the relevant location with a simple workaround.)
    • Added SnapsToDevicePixels=True to applicable elements in the copied style definitions. (Silverlight doesn't support SnapsToDevicePixels in Beta 1, so this property isn't used by the default Beta 1 control templates.)
    • Updated the assembly name for some XAML used by the unit tests.
    • More details: Search the solution for comments with the text "LB-SV-WPF:"
  • Because they're relevant, here are a few details from the previous post:

    What's the meaning of the WPF/WPFIMPLEMENTATION defines in the controls source code? The development of ListBox (+ListBoxItem) and ScrollViewer (+ScrollContentPresenter) was done in parallel with the development of their base types (e.g., ItemsControl, ContentControl) and also in parallel with the development of the Silverlight 2 platform itself. To minimize the risk/impact of developing on a changing foundation, I did much of my development and unit testing on WPF by deriving from the corresponding base classes, using only the subset of WPF that Silverlight exposes, and avoiding features specific to either platform as much as possible.

    When compiling and running on WPF, I would add "WPF" to the list of conditional compilation symbols for the project. Therefore, code inside an #if WPF block applies only when running on WPF. In many cases, the pattern is #if WPF ... #else ... #endif and this corresponds to instances where some bit of code needed to be different between the two platforms (typically because it used features that weren't identical across both). In some cases, the relevant code only applies to one platform and the #else is missing or #if !WPF is used instead.

    The meaning of "WPFIMPLEMENTATION" is similar and is used by the unit tests for code that applies only when testing the WPF implementations of ListBox or ScrollViewer. I used unit tests in three different scenarios to help ensure the code was as correct and compatible as possible: testing the Silverlight implementation on Silverlight, testing the Silverlight implementation on WPF (#if WPF), and testing the WPF implementation on WPF (#if WPF, #if WPFIMPLEMENTATION). Though it may seem silly at first, the point of testing the WPF implementation on WPF was to make sure the unit tests were validating the correct behavior.

[LB-SV-WPF.zip]

LB-SV-FAQ [Examples, Notes, Tips, and More for Silverlight 2 Beta 1's ListBox and ScrollViewer controls!]

Silverlight 2 Beta 1 is available today, yay!! I'm celebrating by publishing an FAQ of sorts for the controls I worked on. While not all of the topics below are "frequently asked questions" (it's a little too soon for that...), they're all intended to help developers get started by covering the basics of these controls.

If you're already familiar with WPF, then Silverlight should come pretty easily to you - but I'd still recommend skimming the topics below because some of the details are unique to Silverlight. If you're new to WPF and Silverlight, then I hope the topics below help jump-start the development process. In either case, I welcome your feedback, so please leave a comment below or contact me with any questions/problems/ideas you have!

Enjoy!!

 

General Questions

What does this FAQ cover? The Silverlight 2 Beta 1 controls I worked on: ListBox, ListBoxItem, ScrollViewer, and ScrollContentPresenter.

Why do all the hyperlinks point to WPF documentation? For one, that's all that was publically available when I started writing this post. For another, the WPF documentation is a superset of the Silverlight documentation and the additional detail there can help clarify issues. And finally, because one of the big goals for the Silverlight controls was complete (subset) compatibility with their WPF counterparts, the WPF documentation has been MY primary reference as well! But sometimes there's no substitute for the real thing; the Silverlight 2 Beta 1 documentation is a great reference, too. :)

What's the meaning of the WPF/WPFIMPLEMENTATION defines in the controls source code? The development of ListBox (+ListBoxItem) and ScrollViewer (+ScrollContentPresenter) was done in parallel with the development of their base types (e.g., ItemsControl, ContentControl) and also in parallel with the development of the Silverlight 2 platform itself. To minimize the risk/impact of developing on a changing foundation, I did much of my development and unit testing on WPF by deriving from the corresponding base classes, using only the subset of WPF that Silverlight exposes, and avoiding features specific to either platform as much as possible.

When compiling and running on WPF, I would add "WPF" to the list of conditional compilation symbols for the project. Therefore, code inside an #if WPF block applies only when running on WPF. In many cases, the pattern is #if WPF ... #else ... #endif and this corresponds to instances where some bit of code needed to be different between the two platforms (typically because it used features that weren't identical across both). In some cases, the relevant code only applies to one platform and the #else is missing or #if !WPF is used instead.

The meaning of "WPFIMPLEMENTATION" is similar and is used by the unit tests for code that applies only when testing the WPF implementations of ListBox or ScrollViewer. I used unit tests in three different scenarios to help ensure the code was as correct and compatible as possible: testing the Silverlight implementation on Silverlight, testing the Silverlight implementation on WPF (#if WPF), and testing the WPF implementation on WPF (#if WPF, #if WPFIMPLEMENTATION). Though it may seem silly at first, the point of testing the WPF implementation on WPF was to make sure the unit tests were validating the correct behavior.

What's a good strategy for investigating possible bugs? If you're trying to do something new and running into behavior that seems wrong, it's often helpful to identify exactly what/where the problem is. My first step is often to try the same scenario on WPF - if the behavior is the same there, then it's probably not a bug (and at least Silverlight is consistent!). But let's say the scenario works fine on WPF - my next step for ListBox problems is to try the same scenario using ItemsControl. This isn't always possible because ItemsControl offers only a subset of ListBox's functionality, but if I'm able to reproduce the problem using just ItemsControl, then ListBox is off the hook and that's a big chunk of code that's no longer in question. If ItemsControl isn't responsible, the next step I'll take is to switch to a debug version of System.Windows.Controls.dll so I can set breakpoints, tweak the control internals, etc.. For bugs in ListBox or ScrollViewer, this should be enough to identify most problems; for bugs in Silverlight, this helps to narrow things down.

And now that you've identified a bug, please let us know so we can fix it! :)

 

Common ListBox Scenarios

Here is the XAML code for a handful of the most common ListBox scenarios along with a picture of what it looks like on Silverlight.

ListBoxItems specified in XAML:

ListBoxItems specified in XAML
<ListBox>
    <ListBoxItem Content="ListBoxItem 0"/>
    <ListBoxItem Content="ListBoxItem 1"/>
    <ListBoxItem Content="ListBoxItem 2"/>
</ListBox>

FrameworkElements specified in XAML:

FrameworkElements specified in XAML
<ListBox>
    <Ellipse Width="20" Height="20"
             Fill="Red" Stroke="Black"/>
    <Rectangle Width="20" Height="20"
               Fill="Blue" Stroke="White"/>
    <Rectangle Width="20" Height="20"
               Fill="Yellow" Stroke="Black"
               RadiusX="5" RadiusY="5"/>
</ListBox>

Objects specified with ItemsSource and StaticResource Binding:

Objects specified with ItemsSource and StaticResource Binding
<ListBox
    ItemsSource="{StaticResource Products}"/>

Horizontal layout with ItemsPanel and ItemsPanelTemplate:

Horizontal layout with ItemsPanel and ItemsPanelTemplate
<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBoxItem Content="Item 0"/>
    <ListBoxItem Content="Item 1"/>
    <ListBoxItem Content="Item 2"/>
</ListBox>

Simple data visualization with DisplayMemberPath:

Simple data visualization with DisplayMemberPath
<ListBox
    ItemsSource="{StaticResource Products}"
    DisplayMemberPath="Name"/>

Complex data visualization with ItemTemplate and DataTemplate:

Complex data visualization with ItemTemplate and DataTemplate
<ListBox ItemsSource="{StaticResource Products}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}"/>
                <TextBlock Text="{Binding Name}"
                           VerticalAlignment="Center"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Customized ListBoxItem appearance with ItemContainerStyle and Style:

Customized ListBoxItem appearance with ItemContainerStyle and Style
<ListBox ItemsSource="{StaticResource Products}"
         DisplayMemberPath="Name">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Background" Value="Gray"/>
            <Setter Property="Foreground" Value="White"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Minimally templated ListBox and ListBoxItem with Template and ControlTemplate:

Minimally templated ListBox and ListBoxItem with Template and ControlTemplate
<ListBox ItemsSource="{StaticResource Products}"
         DisplayMemberPath="Name">
    <ListBox.Template>
        <ControlTemplate TargetType="ListBox">
            <Border BorderBrush="Blue"
                    BorderThickness="2"
                    CornerRadius="5">
                <ItemsPresenter/>
            </Border>
        </ControlTemplate>
    </ListBox.Template>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border BorderBrush="HotPink"
                                BorderThickness="2"
                                CornerRadius="3">
                            <ContentPresenter
                                Content="{TemplateBinding Content}"
                                ContentTemplate="{TemplateBinding ContentTemplate}"
                                FontWeight="Bold"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Note: For the samples that refer to {StaticResource Products}, the following code/XAML is assumed to be present:

namespace LB_SV_FAQ
{
    public class Products : List<Product>
    {
        public Products()
        {
            Add(new Product { Name = "Calculator" });
            Add(new Product { Name = "Notepad" });
            Add(new Product { Name = "Paint" });
        }
    }
    public class Product
    {
        public string Name { get; set; }
        public string Image { get { return Name + ".png"; } }
        public override string ToString() { return "Product: " + Name; }
    }
}
<UserControl x:Class="LB_SV_FAQ.Page"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:LB_SV_FAQ">
    <Grid>
        <Grid.Resources>
            <local:Products x:Key="Products"/>
        </Grid.Resources>
    ...
    </Grid>
</UserControl>

 

ListBox Implementation Notes

Why is SelectionMode.Single the only supported SelectionMode? The Silverlight controls are subsets of their WPF counterparts in order to keep complexity and download size as low as possible. In cases where it seemed that specific functionality was not widely used, we opted to exclude it for Beta 1 and use customer feedback to identify which missing features are the most important. SelectionMode.Multiple and SelectionMode.Extended both fall into the category of "very nice to have, but seemingly not critical for most scenarios" - if you need multiple selection support, please let us know!

Why doesn't ListBox derive from Selector? On WPF, ListBox derives from the Selector class which derives from ItemsControl; on Silverlight, ListBox derives directly from ItemsControl. To simplify matters and keep development/testing/download costs down, the Selector class was thought to be unnecessary for Silverlight 2 Beta 1. With ListBox being the only Selector-derived class in the Beta 1 controls offering, the Selector functionality was merged into ListBox for compactness. (If a Selector class is introduced to the Silverlight controls in the future, it should have little/no effect on existing ListBox code.)

Why does the ListBoxItem.ChangeVisualState method overlap playing the old/new Storyboards? The pattern of changing visual states by calling Begin for the new Storyboard and then calling Stop for the old one is a key part of the Silverlight state model. Starting the new Storyboard begins applying the values of whatever animations it represents (as you'd expect). Stopping the old one then automatically resets any animations it represents that aren't also being changed by the new Storyboard. Manipulating the two Storyboards in this particular manner is necessary for the correct visual behavior under Silverlight.

 

ListBox Curiosities

Why is the scrolling behavior slightly different than with WPF? If you have a ListBox with enough items that a vertical ScrollBar is displayed, using the Page Up/Down or arrow keys to scroll through the list behaves just a little bit differently on Silverlight than on WPF. In particular, WPF's default behavior is to keep the top-most item fully visible and flush against the top of the ListBox at all times. Therefore, scrolling doesn't affect the items' vertical placement until the very beginning/end of the list. Silverlight does not have the same behavior with respect to the top-most item, so the item placement tends to change slightly while scrolling through the list. This behavior difference is due to the fact that the WPF ListBox's default Style overrides the default ScrollViewer.CanContentScroll value of False and sets it to True, changing the ScrollViewer's scrolling mode from physical scrolling (pixel-based) to logical scrolling (item-based). Silverlight's ScrollViewer supports only physical scrolling, so this override is not present on Silverlight. To see the same Silverlight scrolling behavior on WPF, set ScrollViewer.CanContentScroll="False" on any ListBox with ScrollBars.

Why is selection behavior incorrect when I have the same object in a ListBox multiple times? For compatibility with WPF, of course! :) Due to the way ItemsControl is implemented, it is necessary for it to maintain a mapping from the objects it contains to the corresponding wrappers (i.e., ListBoxItems) that get created for them. This is handled by the ItemContainerGenerator.ContainerFromItem method on WPF and by ListBox.GetListBoxItemForObject on Silverlight - but the idea is the same. When the same object reference is added to the ListBox multiple times, this mapping breaks down because it isn't prepared for a single object to map to multiple containers. As it happens, the WPF and Silverlight behaviors differ slightly here. Both seem wrong, but I'll suggest that the Silverlight behavior is slightly less wrong. The following XAML/code demonstrates the problem on WPF and Silverlight (click on the third item, then the second item to see the behavior difference):

<ListBox x:Name="lb"/>
object obj = new object();
lb.Items.Add(obj);
lb.Items.Add(obj);
lb.Items.Add(obj);

Note: The problematic object-to-ListBoxItem mapping is unnecessary when the items added to the ListBox are of type ListBoxItem. Therefore, if you need to store the same object multiple times, consider wrapping your items in unique ListBoxItem instances (setting the Content property to the wrapped item) before adding them to the ListBox.

 

ListBox Bugs

Why doesn't setting ListBox's SelectedIndex in XAML or the Page constructor seem to work? The internal ListBox state is actually correct in the code scenario (and unit tests verify this), but the visual representation is wrong. The following XAML/code demonstrates the problem:

<ListBox x:Name="lb">
    <TextBlock Text="one"/>
    <TextBlock Text="two"/>
    <TextBlock Text="three"/>
</ListBox>
public Page()
{
    InitializeComponent();
    lb.SelectedIndex = 1;
}

The problem is that when the SelectedIndex property gets set in the Page constructor, ItemsControl has not yet called PrepareContainerForItemOverride and so ListBox has not yet set up its mapping from object to ListBoxItem (see the "ListBox Curiosities" section above for more about this mapping). So when ListBox tries to toggle IsSelected on the corresponding ListBoxItem, no such ListBoxItem exists and ListBox gives up instead of making a note to come back and finish this task after the mapping has been established. (Unfortunately, the situation is even worse if SelectedIndex is set in XAML (vs. code) because at that time it is typically the case that ItemsControl's Items collection is still empty.)

The workaround is to call something like the SelectedIndexWorkaround extension method (defined below) after setting SelectedIndex. SelectedIndexWorkaround defers setting SelectedIndex until it will have the desired effect - and thereby works around the bug. The change to the above code is:

lb.SelectedIndex = 1;
lb.SelectedIndexWorkaround();  // Added workaround

Why doesn't setting IsSelected True before adding a ListBoxItem to the ListBox look right? Again the internal ListBox state is correct, but the visual representation is wrong. In this case, the visuals fix themselves if you move the mouse over the selected item and then off it because the ListBoxItem transitions from its hover appearance to its selected appearance and the visuals update correctly. The problem here is that when IsSelected is toggled, ListBoxItem plays its state transition Storyboard immediately - but the ListBoxItem is not in the visual tree yet so Silverlight doesn't actually apply the associated state changes. (To behave correctly in this scenario, ListBoxItem should be calling its ChangeVisualState method at the end of OnApplyTemplate and also in a handler for the Loaded event.) The following code demonstrates the problem:

ListBoxItem lbi;
lbi = new ListBoxItem();
lbi.Content = "Unselected";
lb.Items.Add(lbi);
lbi = new ListBoxItem();
lbi.Content = "Selected";
lbi.IsSelected = true;
lb.Items.Add(lbi);

The workaround is to call something like the IsSelectedWorkaround extension method (defined below) after setting IsSelected. This method causes the appropriate Storyboard to play again once it will have the desired effect - and thereby works around the bug. The change to the above code:

lbi.IsSelected = true;
lbi.IsSelectedWorkaround();  // Added workaround

Why can't I arrow up/down past a ListBox item with Visibility Collapsed? Because ListBox doesn't expect there to be "invisible" ListBoxItems. If you try the obvious workaround of leaving the ListBoxItem Visible and marking its Content Collapsed, arrow navigation no longer gets "stuck" - but the scenario is still confusing to the user because the ListBox lets focus get set to the "invisible" item. Rather than playing with Visibility, consider the more direct approach of removing items from the collection if you don't want them to be visible. An elegant approach is to use an ObservableCollection for storing items and then assign that collection to the ItemsSource property of the ListBox. Because ObservableCollection implements INotifyCollectionChanged, changes to it (e.g., via Add/Remove) are automatically communicated to ListBox's ItemsControl base class which automatically updates the ListBox display. All you need to do is keep the collection up to date - everything else is handled for you.

 

ListBox Workaround Code

The following C# static class implementation can be added to a project to introduce extension methods to help work around the bugs described above. Simply call the corresponding extension method after setting one of the associated properties and the proper behavior should occur. Please note that calling these methods is not typically necessary and should be done only if a scenario is affected by one of the above bugs.

Sorry for the trouble!

/// <summary>
/// This class contains extensions to help work around two ListBox bugs in
/// the Silverlight 2 Beta 1 controls release. Simply add it to your project
/// and call the extension methods just after the properties they match.
/// </summary>
public static class ListBoxExtensions
{
    /// <summary>
    /// Augments ListBox.SelectedIndex to work around a bug where setting
    /// SelectedIndex before the ListBox is visible does not update the UI.
    /// </summary>
    /// <remarks>
    /// Instead of:
    ///     listBox.SelectedIndex = 1;
    /// Use:
    ///     listBox.SelectedIndex = 1;
    ///     listBox.SelectedIndexWorkaround();
    /// </remarks>
    /// <param name="listBox">Extension method class.</param>
    public static void SelectedIndexWorkaround(this ListBox listBox)
    {
        int selectedIndex = listBox.SelectedIndex;
        bool set = false;
        listBox.LayoutUpdated += delegate
        {
            if (!set)
            {
                // Toggle value to force the change
                listBox.SelectedIndex = -1;
                listBox.SelectedIndex = selectedIndex;
                set = true;
            }
        };
    }
    /// <summary>
    /// Augments ListBoxItem.IsSelected to work around a bug where setting
    /// IsSelected before the ListBoxItem is visible does not update the UI.
    /// </summary>
    /// <remarks>
    /// Instead of:
    ///     listBoxItem.IsSelected = true;
    /// Use:
    ///     listBoxItem.IsSelected = true;
    ///     listBoxItem.IsSelectedWorkaround();
    /// </remarks>
    /// <param name="listBoxItem">Extension method class.</param>
    public static void IsSelectedWorkaround(this ListBoxItem listBoxItem)
    {
        bool isSelected = listBoxItem.IsSelected;
        bool set = false;
        listBoxItem.LayoutUpdated += delegate
        {
            if (!set)
            {
                // Toggle value to force the change
                listBoxItem.IsSelected = !isSelected;
                listBoxItem.IsSelected = isSelected;
                set = true;
            }
        };
    }
}

 

Common ScrollViewer Scenarios

Using ScrollViewer to scroll content that is too large:

Using ScrollViewer to scroll content that is too large
<!-- Grid used to limit ScrollViewer size -->
<Grid Width="150" Height="70">
    <ScrollViewer HorizontalScrollBarVisibility="Auto"
                  VerticalScrollBarVisibility="Auto">
        <TextBlock Text="ScrollViewer"
                   FontFamily="Arial Black"
                   FontSize="50"/>
    </ScrollViewer>
</Grid>

Using ScrollViewer to add ScrollBars to an application when the browser is resized:

<UserControl x:Class="ResizableApplication.Page"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <ScrollViewer HorizontalScrollBarVisibility="Auto"
                      VerticalScrollBarVisibility="Auto">
            <Grid>
                <!-- Page content goes here instead of the outer Grid -->
            </Grid>
        </ScrollViewer>
    </Grid>
</UserControl>

 

ScrollViewer Implementation Notes

Why am I having a hard time specifying ScrollViewer's attached properties in XAML? Silverlight 2 Beta 1's XAML parser throws a XamlParseException (ex: "Unknown attribute ScrollViewer.VerticalScrollBarVisibility on element ListBox.") when trying to specify any control's attached properties on a different control in XAML. This problem should be fixed in a future release; for now there's an easy workaround: add an explicit xmlns definition for System.Windows.Controls and use that xmlns when setting the attached properties:

<UserControl x:Class="LB_SV_FAQ.Page"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls">
    <Grid>
        <ListBox controls:ScrollViewer.VerticalScrollBarVisibility="Hidden"/>
    </Grid>
</UserControl>

Why doesn't ScrollViewer support the ScrollViewer.CanContentScroll property? See the "ListBox Implementation Notes" section above for an explanation of how Silverlight controls try to be a minimal subset of core functionality and the "ListBox Curiosities" section for an explanation of how the lack of ScrollViewer.CanContentScroll affects ListBox.

Why is there no ScrollChanged event or IScrollInfo interface? As with ScrollViewer.CanContentScroll, these were deliberate omissions intended to keep things simple and compact.

 

ScrollViewer Curiosities

Why does the ScrollViewer default to HorizontalScrollBarVisibility Disabled and VerticalScrollBarVisibility Visible? For compatibility with the WPF defaults, of course. :) Regarding the obvious next question about why those values are the WPF defaults, I don't know. Auto/Auto would seem more generally useful to me and, in fact, the WPF ListBox (and Silverlight ListBox) overrides the ScrollViewer defaults to set Auto/Auto! But maintaining compatibility wins, so the Silverlight ScrollViewer defaults to the same values used by WPF.