Multiple selection ListBox

In a forum post poster wanted to how to do multiple selection. To be honest, I thought the listbox supports it. Anyway, looks like there is a sample implementation using checkbox. The sample involves changing the datasource.

Here is a version using ToggleButton and styles, without changing the datasource

we create a listbox setting the ItemContainer style

<ListBox Height=”200″
VerticalAlignment=”Top”
x:Name=”list1″
ItemContainerStyle=”{StaticResource ListBoxItemStyle}” />

The style is defined like this

<ToggleButton Click=”ToggleButton_Click”
Content=”{TemplateBinding Content}”
ContentTemplate=”{StaticResource dt}”
Style=”{StaticResource ToggleButtonStyle1}” />

the style for the ToggleButton is defined like this

<Style x:Key=”ToggleButtonStyle1″
               TargetType=”ToggleButton”>
            <Setter Property=”Padding”
                    Value=”3″ />
            <Setter Property=”HorizontalContentAlignment”
                    Value=”Left” />
            <Setter Property=”VerticalContentAlignment”
                    Value=”Top” />
            <Setter Property=”Background”
                    Value=”Transparent” />
            <Setter Property=”BorderThickness”
                    Value=”1″ />
            <Setter Property=”TabNavigation”
                    Value=”Local” />
            <Setter Property=”Template”>
                <Setter.Value>
                    <ControlTemplate TargetType=”ToggleButton”>
                        <Grid x:Name=”grid1″>
                            <vsm:VisualStateManager.VisualStateGroups>
                                <vsm:VisualStateGroup x:Name=”CommonStates”>
                                    <vsm:VisualState x:Name=”Normal” />
                                    <vsm:VisualState x:Name=”MouseOver”>
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetName=”fillColor”
                                                                           Storyboard.TargetProperty=”Opacity”>
                                                <SplineDoubleKeyFrame KeyTime=”0″
                                                                      Value=”.35″ />
                                            </DoubleAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name=”Pressed”>
                                        <Storyboard />
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name=”Disabled”>
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetName=”contentPresenter”
                                                                           Storyboard.TargetProperty=”Opacity”>
                                                <SplineDoubleKeyFrame KeyTime=”0″
                                                                      Value=”.55″ />
                                            </DoubleAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                </vsm:VisualStateGroup>
                                <vsm:VisualStateGroup x:Name=”CheckStates”>
                                    <vsm:VisualState x:Name=”Checked”>
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetName=”fillColor2″
                                                                           Storyboard.TargetProperty=”Opacity”>
                                                <SplineDoubleKeyFrame KeyTime=”0″
                                                                      Value=”.75″ />
                                            </DoubleAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name=”Unchecked”>
                                        <Storyboard>

                                        </Storyboard>
                                    </vsm:VisualState>
                                </vsm:VisualStateGroup>
                                <vsm:VisualStateGroup x:Name=”FocusStates”>
                                    <vsm:VisualState x:Name=”Focused”>
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Duration=”0″
                                                                           Storyboard.TargetName=”FocusVisualElement”
                                                                           Storyboard.TargetProperty=”Visibility”>
                                                <DiscreteObjectKeyFrame KeyTime=”0″>
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name=”Unfocused” />
                                </vsm:VisualStateGroup>
                            </vsm:VisualStateManager.VisualStateGroups>
                            <Rectangle x:Name=”fillColor”
                                       IsHitTestVisible=”False”
                                       Opacity=”0″
                                       Fill=”#FFBADDE9″
                                       RadiusX=”1″
                                       RadiusY=”1″ />
                            <Rectangle x:Name=”fillColor2″
                                       IsHitTestVisible=”False”
                                       Opacity=”0″
                                       Fill=”#FFBADDE9″
                                       RadiusX=”1″
                                       RadiusY=”1″ />
                            <ContentPresenter HorizontalAlignment=”Left”
                                              Margin=”{TemplateBinding Padding}”
                                              x:Name=”contentPresenter”
                                              Content=”{TemplateBinding Content}”
                                              ContentTemplate=”{TemplateBinding ContentTemplate}” />
                            <Rectangle x:Name=”FocusVisualElement”
                                       Visibility=”Collapsed”
                                       Stroke=”#FF6DBDD1″
                                       StrokeThickness=”1″
                                       RadiusX=”1″
                                       RadiusY=”1″ />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
Thats all for the styles. When the ToggleButton is clicked, we will have code similar to the following
where we will use couple of helper functions

private void ToggleButton_Click(object sender, RoutedEventArgs e)
{
ListBoxItem lbi = GetParent(sender as DependencyObject);
if ((sender as ToggleButton).IsChecked.Value)
lbi.Tag = (sender as ToggleButton).DataContext;
else
lbi.Tag = null;
}

When it is time to find all the Items that are selected in the listbox. we get the stackpanel and get its children

StackPanel sp = GetChild(list1);
List mylist = sp.Children.Cast().Where(ele => ele.Tag != null).ToList();

you can see a demo or download the code here

Advertisements

7 thoughts on “Multiple selection ListBox

  1. Hi Lee, your post is very helpful. I have one question though. How can I pre-select some entries in the List Box using this method. Lets say I have to highlight 2 selected List Box Items when loading, I just know the Id and Text of those items, how can I do that.
    Thanks in advance.

    1. Multiple selection feature is in Silverlight 3. I suggest you use that. if you still have to use this. did you take a look at the previous comment

  2. Hi,
    This is a hack, but will work
    you could add a eventhandler for the loaded event of the Togglebutton in the style
    private void ToggleButton_Loaded(object sender, RoutedEventArgs e)
    {
    ToggleButton btn = (sender as ToggleButton);
    List selectedPersons = “your list of persons to be selected by default”;
    if (selectedPersons.Contains(btn.DataContext as Person))
    {
    btn.IsChecked = true;
    ListBoxItem lbi = GetParent(sender as DependencyObject);
    lbi.Tag = btn.DataContext;
    }
    }

  3. Hi Lee, Your post is helpful. But I have one question how can I select all the items at a time in the listbox.

    One more question is if I click on the white space beside the displayname that item is not selecting how can acheive the above two scenarios. Can you please give your suugestions.

    Thanks,
    KOnda

  4. Hi Lee, Your post is helpful. But I have one question how can I select all the items at a time in the listbox.
    One more question is if I click on the white space beside the displayname that item is not selecting how can acheive the above two scenarios. Can you please give your suugestions.
    Thanks,
    Anaconda

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s