user1202434
user1202434

Reputation: 2273

ItemsPanelTemplate Selector in wpf?

I need to set the ItemsPanelTemplate property of a listbox based on a dependency property on the control. How do I use the DataTemplateSelector to do that?

I have something like:

<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <!-- Here I need to replace with either a StackPanel or a wrap panel-->
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>

Thanks

Upvotes: 8

Views: 5395

Answers (2)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84674

There isn't an ItemsPanelSelector (probably because it isn't a DataTemplate) but you can bind it or use a Trigger

Binding example

<ListBox ItemsPanel="{Binding RelativeSource={RelativeSource Self},
                              Path=Background,
                              Converter={StaticResource MyItemsPanelConverter}}">

Trigger in Style example

<ListBox ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
    <ListBox.Style>
        <Style TargetType="ListBox">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <StackPanel/>
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <!-- Your Trigger.. -->
                <Trigger Property="Background" Value="Green">
                    <Setter Property="ItemsPanel">
                        <Setter.Value>
                            <ItemsPanelTemplate>
                                <WrapPanel/>
                            </ItemsPanelTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.Style>
</ListBox>

Upvotes: 19

Tim
Tim

Reputation: 15247

I'm thinking the best route here would be to use a Style for your ListBox and set Triggers that change the ItemsPanel based on the DependencyProperty you reference.

Upvotes: 0

Related Questions