views:

210

answers:

2

Are there any slick ways to style/template a WPF ItemsControl differently based off whether ItemsSource holds a single value or multiple values?

What I've done so far is to create a custom ItemsControl class which among other things displays the list of bound items as a horizontally oriented comma separated list. So far I'm pretty happy with the results however I want to show a more brief view of the bound data in cases where multiple values are bound and if only a single value is bound then I want to show a more extended view of the bound data with a longer string description. I figure this is probably best solved by dynamically choosing the template either based off a trigger or possibly by using a template selector but it's not yet clear to me how this would be done.

+3  A: 

You could use a DataTrigger in your style to replace the template:

<Style.Triggers>
    <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Items.Count}" Value="1">
        <Setter Property="Template">
            <Setter.Value>
                <!-- Insert Template here -->
            </Setter.Value>
        </Setter>
    </DataTrigger>
</Style.Triggers>

You could also add one for where the Value is 0 if you wanted to display a "no records" template.

Steven Robbins
I was just attempting to implement it this way. So I guess the idea would be to have the default template define the default multi-value behavior but then to handle a Count = 1 as a special case by using a trigger as you demonstrated. Does this sound right?
jpierson
Yep, that sounds right. It should also automatically switch between them when the count changes.
Steven Robbins
Thanks, this technique works great for the situation I described above. Unfortunately I realized my case is a bit different in that I'm actually only interested in the number of items that are marked as IsSelected in my ItemsSource as opposed to the raw Count. Unfortunately I don't see an easy way to apply the same concept but I think your solution adequately addresses the question I originally posed.
jpierson
A: 

You should use a StyleSelector. Here is a sample.

Muad'Dib