Search code examples
wpfmarginitemscontrol

WPF Different item's margin on ItemsControl


I have the following ItemsControl:

<ItemsControl x:Name="ListResult">
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <DockPanel>
            <Image Margin="10,0,0,0"
                   Source="{Binding Pic}"/>
            <TextBlock Text={Binding Info}/>
         </DockPanel>
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

I bind the ItemsControl's ItemsSource to a List<>.

Is it possible to put a different margin for each item?

For example:

ListResult[0].Margin="10,0,0,0";
ListResult[1].Margin="50,0,0,0";
ListResult[2].Margin="10,0,0,0";
ListResult[3].Margin="50,0,0,0";

Solution

  • If you mean to alternate between lines : from : WPF: Alternating colors on a ItemsControl? I changed @biju commant to Margin

    <ItemsControl ItemsSource="{Binding ListResult}" AlternationCount="2">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <DockPanel>
                    <Image x:Name="image" Source="{Binding Pic}"/>
                    <TextBlock Text="{Binding Info}"/>
                </DockPanel>
                <DataTemplate.Triggers>
                    <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                        <Setter Property="Margin" Value="10,0,0,0" TargetName="image"/>
                    </Trigger>
                    <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                        <Setter Property="Margin" Value="50,0,0,0" TargetName="image"/>
                    </Trigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>