2
votes

My WPF ListBox contains two types of object: Product and Brand.

I want my Products selectable. I want my Brands not selectable.

Each of the two types has its own DataTemplate.

By default, anything may be selected:

<ListBox ... >
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type local:Product}">
            ...
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:Brand}">
            ...
        </DataTemplate>
    </ListBox.Resources>
</ListBox>

I can set Focusable with a Setter, but then nothing may be selected:

<ListBox ... >
    <ListBox.Resources>
        ...
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Focusable" Value="False" />
        </Style>
    </ListBox.Resources>
</ListBox>

I cannot put the Setter within the DataTemplate.

I cannot put a DataType onto the Style.

How do I style only the ListBoxItems of type Brand?

2

2 Answers

2
votes

Thanks to the StyleSelector class you can attach styles depending on type of data for the ItemContainerStyle. There is a really good example here : http://www.telerik.com/help/wpf/common-data-binding-style-selectors.html

1
votes

Can you use a data trigger on your ListBoxItem style? If so, bind to the DataContext (your class) and use a value converter to test the type. If it's the one you're interested in, style the ListBoxItem so that it cannot appear selected.

I don't think you can disallow selection of an item in a Selector (parent of ListBox) without codebehind or a custom Behavior.