Wpf How to change List box ItemspanelTemplate using Trigger
As the error say's your trying to set a Style
when it's expecting an ItemsPanelTemplate
as Setter.Value
. Define your resources as ItemPanelTemplate
's than ListBox
Style
's and you should be sorted
Try something like:
<ListBox Name="lv" Background="LightBlue" FontSize="12" ItemsSource="{Binding Source={StaticResource myXmlDataBase}, XPath=Item}"> <ListBox.Resources> <ItemsPanelTemplate x:Key="ListBoxWrapTemplate"> <WrapPanel Width="{Binding (FrameworkElement.ActualWidth), RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}" ItemHeight="{Binding (ListView.View).ItemHeight, RelativeSource={RelativeSource AncestorType=ListView}}" ItemWidth="{Binding (ListView.View).ItemWidth, RelativeSource={RelativeSource AncestorType=ListView}}" /> </ItemsPanelTemplate> <ItemsPanelTemplate x:Key="ListBoxHorizontalStackTemplate"> <StackPanel Width="{Binding (FrameworkElement.ActualWidth), RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}" Orientation="Horizontal" /> </ItemsPanelTemplate> <ItemsPanelTemplate x:Key="ListBoxVerticalStackTemplate"> <StackPanel Width="{Binding (FrameworkElement.ActualWidth), RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}" Orientation="Vertical" /> </ItemsPanelTemplate> </ListBox.Resources> <ListBox.Style> <Style TargetType="ListBox"> <Style.Triggers> <!-- Your Trigger.. --> <Trigger Property="Background" Value="Green"> <Setter Property="ItemsPanel" Value="{DynamicResource ListBoxVerticalStackTemplate}" /> </Trigger> <Trigger Property="Background" Value="LightBlue"> <Setter Property="ItemsPanel" Value="{DynamicResource ListBoxHorizontalStackTemplate}" /> </Trigger> <Trigger Property="Background" Value="LightGreen"> <Setter Property="ItemsPanel" Value="{DynamicResource ListBoxWrapTemplate}" /> </Trigger> </Style.Triggers> </Style> </ListBox.Style> ...
I was wondering why Viv's answer did not work in my case :-(Here is what I did wrong:
Do not define the ItemsPanelTemplate appart from the <Style.Triggers>
!If you place one in the <Listbox.ItemPanel></Listbox.ItemPanel>
the style triggers won't have any effect.
Arnaud.
ps: no sufficient reputation to only comment...