Florian
Florian

Reputation: 5994

Listbox style selection does not work with datatemplate

I am using a ListBox and a ListBox style from here: http://viblend.com/products/net/wpf/controls/free-wpf-controls.aspx

That looks like this:

    <ListBox x:Name="listBox" ItemsSource="{Binding}" Style="{StaticResource Office2010SilverListBoxStyle}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ListBoxItem Style="{StaticResource Office2010SilverListBoxItemStyle}" Content="{Binding}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

But if I am clicking on an item it gets not marked as selected item. If i am using no datatemplate all works fine. So does anyone has any idea why? Here the working example:

<ListBox x:Name="listBox" Style="{StaticResource Office2010SilverListBoxStyle}">
    <ListBoxItem Style="{StaticResource Office2010SilverListBoxItemStyle}">1. Frame</ListBoxItem>
    <ListBoxItem Style="{StaticResource Office2010SilverListBoxItemStyle}">2. Frame</ListBoxItem>
    <ListBoxItem Style="{StaticResource Office2010SilverListBoxItemStyle}">3. Frame</ListBoxItem>
    <ListBoxItem Style="{StaticResource Office2010SilverListBoxItemStyle}">4. Frame</ListBoxItem>
    <ListBoxItem Style="{StaticResource Office2010SilverListBoxItemStyle}">5. Frame</ListBoxItem>
    <ListBoxItem Style="{StaticResource Office2010SilverListBoxItemStyle}">6. Frame</ListBoxItem>
</ListBox>-->

Upvotes: 2

Views: 459

Answers (1)

brunnerh
brunnerh

Reputation: 184316

Your DataTemplate should not contain a ListBoxItem, that will be created by the ListBox control already, in your example there will be a ListBoxItem in a ListBoxItem, confuses selection.

Also you should apply the style to the items via ItemContainerStyle. (As far as i know this only works for auto-generated ListBoxItems which are created if you add data either directly or via ItemsSource, if you add ListBoxItems directly both DataTemplate and the ItemContainerStyle will be ignored)

See also: Data Templating Overview

Upvotes: 1

Related Questions