In this article I want to extend my ItemsControl.Style, by binding template.
XAML:
<Grid> <Grid.Resources> <itemsControlItemTemplate:ItemsControlViewModel x:Key="ItemsControlViewModel" /> </Grid.Resources> <ItemsControl DataContext="{StaticResource ItemsControlViewModel}" ItemsSource="{Binding myItemsSource}"> <ItemsControl.Style> <Style TargetType="ItemsControl"> <Style.Triggers> <DataTrigger Binding="{Binding ParentMyItemType}" Value="{x:Static itemsControlItemTemplate:myItemTypes.WrapPanel}"> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <WrapPanel /> </ItemsPanelTemplate> </Setter.Value> </Setter> </DataTrigger> <DataTrigger Binding="{Binding ParentMyItemType}" Value="{x:Static itemsControlItemTemplate:myItemTypes.StackPanel}"> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <StackPanel /> </ItemsPanelTemplate> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers> </Style> </ItemsControl.Style> <ItemsControl.ItemTemplate> <DataTemplate> <DataTemplate.Resources> <itemsControlItemTemplate:AnotherModel x:Key="AnotherModel" /> </DataTemplate.Resources> <Label DataContext="{StaticResource AnotherModel}" Content="{Binding myContent}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid>
Here notice part, for example:
<DataTrigger Binding="{Binding ParentMyItemType}" Value="{x:Static itemsControlItemTemplate:myItemTypes.WrapPanel}"> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <WrapPanel /> </ItemsPanelTemplate> </Setter.Value> </Setter> </DataTrigger>
Where myItemTypes.WrapPanel I declared something like:
public enum myItemTypes { WrapPanel, StackPanel }
and then my view model looks like:
public class ItemsControlViewModel { public IEnumerable<string> myItemsSource { get; set; } public myItemTypes ParentMyItemType { get; set; } public ItemsControlViewModel() { myItemsSource = new[] { "Test1", "Test2" }; this.ParentMyItemType = myItemTypes.WrapPanel; } } public class AnotherModel { public string myContent { get; set; } public AnotherModel() { myContent = "test2"; } }
notice line:
this.ParentMyItemType = myItemTypes.WrapPanel;
with that line I said that I want my style to be with StackPanel.
Example code you can download from here.