Something Like For Loop in XAML

wpf, xaml

Solution

There's nothing like `for` in XAML, but `ItemsControl` is very much like `foreach`. Instead of setting an `int` property, make an `ObservableCollection<T>` and add that many objects to it, and then bind the `ItemsControl` to your collection property.

This has the added benefit that each collection item can expose properties to be bound, e.g. if you wanted to display different text in each `TextBlock`, you could put a property on your collection item and bind the `TextBlock` to that property.

Problem

I have a Resource Dictionary in which I want to have a common DataTemplate for ComboBox. ``` <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <DataTemplate DataType="{x:Type ComboBox}"> <StackPanel Orientation="Horizontal"> <!--Here I need to use something like For Loop--> <TextBlock Text=""></TextBlock> </StackPanel> </DataTemplate> </ResourceDictionary> ``` Now I have created a dependency property of type integer named NoOfColumns. While declaring the comboBox I need to set the NoOfColumns property to automatically generate that number of columns. I want them to `databind`. Update as requested by Joe ``` <ComboBox x:Name="cbUnder" ItemsSource="{Binding GroupsAndCorrespondingEffects}" IsEditable="True" SelectedItem="{Binding SelectedGroup, Mode=TwoWay}" Text="{Binding InputValue, UpdateSourceTrigger=PropertyChanged}" TextSearch.TextPath="GroupName" Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="3"> <ComboBox.Resources> <DataTemplate DataType="{x:Type vm:GroupAndCorrespondingEffect}"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding GroupName}" Width="250"> <TextBlock.Style> <Style TargetType="TextBlock"> <Style.Triggers> <DataTrigger Binding="{Binding IsHighlighted}" Value="True"> <Setter Property="Foreground" Value="Blue" /> <Setter Property="FontWeight" Value="Bold"/> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> <TextBlock Text="{Binding CorrespondingEffect}" /> </StackPanel> </DataTemplate> </ComboBox.Resources> </ComboBox> ```

Original source