Welcome to MSDN Blogs Sign in | Join | Help

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.

 

Published Wednesday, March 05, 2008 4:12 PM by Delay
Filed under:

Comments

# Finally arrived Silverlight 2 Beta 1

Wednesday, March 05, 2008 7:59 PM by Connect Wireless

Here comes the Silverlight 2 Beta 1. Go ahead download here and read about the new features of Silverlight

# Finally arrived Silverlight 2 Beta 1

Wednesday, March 05, 2008 8:30 PM by Noticias externas

Here comes the Silverlight 2 Beta 1. Go ahead download here and read about the new features of Silverlight

# Silverlight 2 ListBox, ListBoxItem, ScrollViewer, and ScrollContentPresenter - from the horses mouth.

Thursday, March 06, 2008 12:52 PM by andyBlog [andy britcliffe]

If you're digging into Silverlight 2 and the controls available then you should check out Delay's blog

# Silverlight Cream for March 6, 2008 -- #212

Thursday, March 06, 2008 1:18 PM by Community Blogs

This is going to be not only BUSY... but is going to take a while on this connection. I think I&#39;m

# Silverlight Cream for March 6, 2008 -- #212

Thursday, March 06, 2008 1:39 PM by Community Blogs

This is going to be not only BUSY... but is going to take a while on this connection. I think I&#39;m

# Silverlight 2 ListBox, ListBoxItem, ScrollViewer, and ScrollContentPresenter - from the horses mouth.

Thursday, March 06, 2008 1:57 PM by Noticias externas

If you&#39;re digging into Silverlight 2 and the controls available then you should check out Delay&#39;s

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

Monday, March 10, 2008 7:28 PM by Delay's Blog

In the Silverlight 2 ListBox/ScrollViewer FAQ , I mentioned that I'd done a lot of Silverlight control

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

Monday, March 10, 2008 8:20 PM by Noticias externas

In the Silverlight 2 ListBox/ScrollViewer FAQ , I mentioned that I&#39;d done a lot of Silverlight control

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

Wednesday, March 12, 2008 5:00 PM by Delay's Blog

In my Silverlight 2 ListBox/ScrollViewer FAQ I described some common scenarios and demonstrated how to

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

Wednesday, March 12, 2008 5:26 PM by Noticias externas

In my Silverlight 2 ListBox/ScrollViewer FAQ I described some common scenarios and demonstrated how to

# Hooking Data up to ListBox and Datagrid

Tuesday, March 18, 2008 3:36 PM by Ux Musings

I wanted to create a quick walkthrough of how to hook data up to both ListBox and Datagrid. In this walkthrough,

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

Tuesday, March 18, 2008 3:39 PM by CorrinaB

Delay’s blog has some great info on how to use ListBox in various ways (he covers most of the key scenarios for how to use listbox) that will be a great thing to check out as well as this post...

# Silverlight 2 Resource

Wednesday, March 26, 2008 11:50 AM by Canadian User Experience

It has been three weeks since we annouced Silverlight 2 at MIX08. Many of you are excited to getting

# Listbox default behaviors

Thursday, March 27, 2008 2:36 PM by EranSun

Hi....

I'll say 1st that I'm a designer and not a developer, sorry ( can you talk slowly .. ^_^ )

I can't seem to find any reference on how to override the default behaviors of the list box such as:

1.the 1px gray line separator between items on the list box

2. the on Hover gradient.

3. the selected item gradient.

4. margin/padding between items.

5. *changing the look of the scrollviewer.

6. scrolling without scrollviewer.

Thanx a lot..

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

Thursday, March 27, 2008 3:53 PM by Delay

EranSun,

Please have a look at the "Minimally templated ListBox and ListBoxItem with Template and ControlTemplate" example in my blog above for your points 1, 2, 3, 4, and 5. The very basic styling I've done there should already demonstrate 1 and 4 - and the general technique is exactly what you'd do for 2, 3, and 5. Briefly, it's just a matter of providing your own custom template for the control - possibly starting from the default template for reference. For 6, you'd probably want to use ScrollBar directly - it exposes the necessary events to do proper scrolling, though it probably takes a bit of code to hook everything up. In general, ScrollViewer should meet most scrolling needs, but when it doesn't, ScrollBar should do the trick.

For more on a few of the techniques I've mentioned (total look customization, default template access, etc.), please have a look at some of my other Silverlight posts and samples: http://blogs.msdn.com/delay/archive/tags/Silverlight/default.aspx

Hope this helps!

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

Friday, March 28, 2008 10:13 AM by EranSun

Thank you very much...

after I've read your post on minimally templated ListBox, I got the syntax of the writing but I don't understand/know the properties/"setter" for changing the styling,

like what is the setter for seperator/onhover/selected ..

Sorry for petty comments

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

Friday, March 28, 2008 6:27 PM by Delay

EranSun,

I've found the MSDN documentation on Silverlight Control customization very helpful for learning about this stuff:

http://msdn2.microsoft.com/en-us/library/cc278068(vs.95).aspx

The default styles/templates for ListBox/ListBoxItem are part of that documentation and are here:

http://msdn2.microsoft.com/en-us/library/cc278062(vs.95).aspx

To specifically address your questions, you're probably going to want to specify a custom ListBoxItem template (using the ListBox.ItemContainerStyle property I demonstrate in the FAQ should do nicely):

* Removing the separator is simply a matter of removing the <Line> element near the bottom of the ListBoxItem template

* The default selected appearance is specified by the "Normal Selected State" state

* The default hover state is specified by the "MouseOver State"

* The "MouseOver Selected State" represents the selected AND hovered appearance

Good luck!

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

Saturday, March 29, 2008 9:13 AM by EranSun

Thank you very much,

It is a great help..

^_^

More then happy to invite you to our private beta very soon !!!

www.semantinet.com :)

# Silverlight Tips, Tricks, Tutorials and Links Page

Wednesday, April 02, 2008 5:03 AM by ScottGu's Blog

I'll be using this page to link to Silverlight 2 articles and posts (both ones I write as well ones by

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

Thursday, April 10, 2008 6:31 AM by jeanf

Just a question, in a ListBox I have among other controls a TaxtBlock with long text, so I configured TextBlock to wrap but in the listbox it's allways on one line with horizontal scrolling.

How can I force TextBlock to wrap text at the ListBox width ?

Thanks for your help

Jean (jeanf@afp.com)

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

Thursday, April 10, 2008 3:23 PM by Delay

Jean,

By default, ListBoxItems are allowed to grow as large as they want and ListBox introduces ScrollBars if the content gets too big. You'll see the same behavior you describe on both WPF and Silverlight. If you want to constrain the width of the ListBoxItems, then one easy way is to introduce a Width restriction on them via ListBox.ItemContainerStyle. The following XAML behaves as you want for Silverlight and WPF:

<ListBox Width="100">

   <TextBlock Text="This is some test text to use for looking at wrapping" TextWrapping="Wrap"/>

   <TextBlock Text="More text to wrap" TextWrapping="Wrap"/>

   <ListBox.ItemContainerStyle>

       <Style TargetType="ListBoxItem">

          <Setter Property="Width" Value="94"/>

       </Style>

   </ListBox.ItemContainerStyle>

</ListBox>

(Note that I've chosen the value 94 because the ListBox's border takes up 6 pixels on Silverlight and 100-6=94.)

# Buttons in a ListBox, and More [Demonstration of some useful Silverlight techniques]

Monday, April 21, 2008 3:17 PM by Delay's Blog

One scenario I've seen cause a bit of trouble on the Silverlight Controls Forum is that of putting a

# Please add multiple selection support

Wednesday, April 30, 2008 12:02 PM by asterite

Please, please, please, add support for multiple selection. In our current application we need to select some elements and drag them somewhere else in order to trigger an action. We also need to be able to select multiple elements and show their common properties. And I can imagine many other scenarios where multiple selection is a must.

Thanks,

Ary

# IValueConverter: The Swiss Army Knife of Bindings [PropertyViewer sample is a WPF/Silverlight visualization and debugging aid!]

Sunday, May 04, 2008 7:23 PM by Delay's Blog

If you've made much use of data binding in WPF or Silverlight, you've probably come across the IValueConverter

# Please add multiple selection support

Tuesday, June 17, 2008 2:22 PM by robmaransky

Multiple selection is important for us as well

# Listbox - SelectionMode

Friday, June 20, 2008 5:06 AM by Community Blogs

One of the features I am missing at the moment from Silverlight 2 is SelectionMode=”Multiple” for Listboxes

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

Sunday, June 29, 2008 11:46 PM by Miguel Madero

Delay,

In the Workaround for the Listbox, shouldnt you unsubscribe of the event (instead of using a flag), Woldnt it cause the static anonymous delegate to hold a reference to the control that will cause it to dont be released properly by the GC.

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

Monday, June 30, 2008 1:13 AM by Delay

Miguel,

That seems like a great suggestion! When I wrote the workarounds, I was more interested in demonstrating the concept than providing production-ready code and that's probably why I didn't complicate the examples with clean-up code. However, as I think about it now in response to your question, I'm not sure unsubscribing would really have added that much complexity, so I'm thinking I should have just done so in the interest of correctness. At any rate, I agree with you - though both workarounds should become unnecessary in an upcoming Silverlight update. :)

Thanks very much for your feedback!

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

Monday, June 30, 2008 4:07 AM by Miguel Madero

Delay,

It's great this will be fixed in an next update :) and I like the approach you took to encapsulate it in an Extension Method, that way it can easily be spotted and removed when needed and in the meantime provides ease of use and code reuse.

I'll post another comment with a bug (weird behavior) I found.

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

Monday, June 30, 2008 12:04 PM by Miguel Madero

Delay,

I have more information and workarounds under this topic, but everytime I try to post it, I'm redirected to the homepage of your blog. So I will be brief. If you need greated detail you can check the Silverlight forum:

http://silverlight.net/forums/p/19509/66596.aspx#66596

The SelectionChanged event is launched before the item is actually selected. It should be called SelectionChanging to reflect what it's actually happening. The problem this is causing is that in that event I'm changing the ItemSource, so by the time the control actually sets the selectedItem (after the evenr was fired), the item is not present in its dictionary and fails. This is the exception.

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

Monday, June 30, 2008 1:55 PM by Delay

Miguel,

Sorry for the trouble with posting to the blog - I rely on the MSDN folks to set things up correctly. :) At any rate, I've replied to your forum post just now - we should continue the discussion there.

Thanks again for your feedback!

# Iterating over the "Controls Collection"create by an ListBox

Friday, July 04, 2008 10:57 AM by Miguel Madero

I know there's probably a better way to do it, at least there's in WinForms and ASP.NET. As always the workaround for me has been databinding, but I thinks it's too much overhead for simple tasks. Probably it all comes down to the fact the SL and WPF are more datacentric rather than controlCentric. Anyway, here's the issue.

It's ok beeing datacentric and sometimes it's easy to get to the data through the controls, i.e. listBox.SelectedItem and listBox.Items will get you a product and a IEnumerable<Products> instead of controls you could iterate over.

Imagine I have nested ListBoxes as shown and I need to get to the selectedItem for each of the inner listBoxes. In this case I dont care about the controls, I only care about the selectedItem (product) but I'd to get to each inner listbox to get it.

<ListBox ItemsSource="{StaticResource Categories}">

   <ListBox.ItemTemplate>

       <DataTemplate>

<StackPanel>

<TextBloc Text="{Binding CategoryName}"

           <ListBox Orientation="Horizontal" ItemsSource="{Binding Products}">

   <ListBox.ItemTemplate>

       <DataTemplate>

               <Image Source="{Binding Image}"/>

               <TextBlock Text="{Binding Name}"

       </DataTemplate>

</ListBox.ItemTemplate>

         </StackPanel>

       </DataTemplate>

   </ListBox.ItemTemplate>

</ListBox>

I wanted to know, what are your toughts about this.

Workaround 1. Databinding. 2. Maintain a temporary dictionary<ListBox,Product> that contains the sender as key and the selectedItem as value and update that on each SelecionChanged event.

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

Saturday, July 05, 2008 3:33 AM by Delay

Miguel,

I like both of your workarounds - and don't have anything more compelling to suggest at the moment. :) For #1, I'm thinking you mean to use a TwoWay Binding to automatically update the source. This seems elegant because when the user is done selecting, your data structure already includes all the selection information you want. For #2, I think this is a bit more work to implement, but I'm more confident that it can be implemented successfully. :)

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

Saturday, July 05, 2008 7:16 PM by Miguel Madero

Delay,

What are your toughts about this for future releases? Would there be a way in the future to get to the inner controls?

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

Monday, July 07, 2008 1:02 AM by Delay

Miguel,

In case you're not familiar with it, there's already the VisualTreeHelper class for both Silverlight and WPF. It lets you walk the visual tree and will let you get a reference to any part of it if you know what you're looking for. It may be useful here, though I didn't mention it before because it didn't seem quite what you were looking for. Regarding future innovation, I don't know where things are headed, so I'm afraid I can't be too helpful there.

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

Tuesday, July 08, 2008 2:18 AM by Miguel Madero

Wow, this looks exactly what I was looking for. It would be nice if GetChild has an overview to get the elements by Name instead of index.

Thanks

# Silverlight 文章收集

Monday, July 21, 2008 10:34 PM by 木野狐(Neil Chen)

(以下内容全部整理自博客堂Scottgu博客中文版)Silverlight技巧,诀窍,教程和链接 【原文地址】SilverlightTips,Tricks,...

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

Wednesday, July 23, 2008 1:37 AM by Miguel Madero

Delay,

A nice improvement for LB would be to offer an Empty Template just like the gridView in ASP.NET does.

:)

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

Wednesday, July 23, 2008 1:48 PM by Delay

Thanks, Miguel! I'll pass this suggestion on to the relevant people.

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

Monday, July 28, 2008 8:27 PM by Miguel Madero

Delay,

In this post you say an option for investigatin possible bugs is to ...'switch to a debug version of System.Windows.Controls.dll so I can set breakpoints'... Can we do this? Is there a version available for this dll?

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

Monday, July 28, 2008 8:38 PM by Delay

Miguel,

In the blog post above, I provide a link to a download for the "Source Code and Unit Tests for Silverlight 2 Beta 1 Controls" [http://www.microsoft.com/downloads/details.aspx?FamilyID=ea93dd89-3af2-4acb-9cf4-bfe01b3f02d4&DisplayLang=en]. In the Beta 1 timeframe, that download was enough for someone to compile their own System.Windows.Controls.dll (containing Button, ListBox, ...), set breakpoints in it, make changes for testing, etc.. With Silverlight Beta 2, most of the controls in that assembly became part of the Silverlight runtime - and the source code for the updated controls was not released by the Silverlight team. However, it's my understanding that source for those controls WILL be available for the Silverlight RTM - and the approach I describe will again become possible.

Hope this helps!

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

Tuesday, July 29, 2008 12:51 PM by Miguel Madero

Too bad :( it would be useful to spot bugs in Beta 2....

Source server might be another good option, instead of releasing as a download.

# Silverlight ListBox SelectedItem/SelectedIndex Visual State Bug Workaround

Friday, August 01, 2008 2:19 PM by adamjcooper.com/blog

Silverlight ListBox SelectedItem/SelectedIndex Visual State Bug Workaround

# ListBox SelectedItem / SelectedIndex Workaround

Friday, August 01, 2008 2:37 PM by adamjcooper

Thanks for the ListBox SelectedItem/SelectedIndex workaround. It was just what I needed for a project.

I did notice though, like Miguel, that your implementation was artificially growing the list of event handlers that needed to be called. So I created a similar version that doesn't suffer from the same problem. But rather than use extension methods which must be called explicitly, I extended ListBox so that the functionality is always present. Works like a charm. Thanks a million.

For anyone else who may be interested, I've posted my implementation at:

http://www.adamjcooper.com/blog/post/Silverlight-ListBox-SelectedItemSelectedIndex-Visual-State-Bug-Workaround.aspx

Adam Cooper

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

Friday, August 01, 2008 2:44 PM by Delay

Thanks, Adam!

# Silverlight ListBox

Tuesday, October 28, 2008 1:25 PM by Philip Richardson | Dynamics CRM

I found this blog post invaluable when trying to debug a personal Silverlight project. The ListBox object

# Silverlight技巧,诀窍,教程和链接

Monday, January 05, 2009 11:19 PM by truejob

Silverlight技巧,诀窍,教程和链接

【原文地址】SilverlightTips,Tricks,TutorialsandLinksPage

我将使用本页链接到有关Silve...

Anonymous comments are disabled
 
Page view tracker