ItemsPanelTemplate Selector in wpf?
Asked Answered
V

2

8

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

Veil answered 18/5, 2012 at 12:26 Comment(0)
C
19

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>
Carleencarlen answered 18/5, 2012 at 13:28 Comment(1)
Great..Thanks for providing code sample..That really helped me out a lot. Thumbs up my friend.Veil
L
0

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.

Li answered 18/5, 2012 at 13:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.