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

Tim
  • 14,999
  • 1
  • 45
  • 68
user1202434
  • 2,243
  • 4
  • 36
  • 53

2 Answers2

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>
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
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.

Tim
  • 14,999
  • 1
  • 45
  • 68