Search code examples
c#silverlightdatatemplateitemscontrolstackpanel

Arranging ItemsControl items within a DataTemplate


For some reason, Items added witin a dataTemplate will not do what I tell them to do!!

I am trying to put a number of images horizontally within a stackpanel, but no matter how I try, they only go vertically.

Here is my xaml.

<DataTemplate x:Name="View">
  <Border BorderBrush="Red" BorderThickness="4" >
      <StackPanel  Orientation="Horizontal">
             <ItemsControl ItemsSource="{Binding Path=_Collection, Mode=OneWay}" >
                 <ItemsControl.ItemTemplate>
                      <DataTemplate >
                          <Image Source="{Binding _Source}" />
                      </DataTemplate>
                 </ItemsControl.ItemTemplate>
             </ItemsControl>
         <TextBlock Height="30" FontFamily="Trebuchet MS" FontSize="18" Text="{Binding _Name}" />
      </StackPanel>
  </Border>
</DataTemplate>

Everything is bound ok. This is called from within the user control proper

<ItemsControl ItemTemplate="{StaticResource siteView}" ItemsSource="{Binding Path=_SiteDisplay"/>

My obervable colletion _SiteDisplay contains another oberservable collection called _Collection which holds the url of the image.

This is cut down from the real code, but illustrates the problem. I can not get the images to align horizontally! Any help very much appreciated - or suggestions for better ways of doing this.


Solution

  • You need to change the panel used by the ItemsControl, not the panel that contains the ItemsControl:

    <ItemsControl ItemsSource="{Binding Path=_Collection, Mode=OneWay}" >
        <ItemsControl.ItemTemplate>
            <DataTemplate >
                <Image Source="{Binding _Source}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate >
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>