c# WPF CellTemplate / DataTemplate for an Image list / array

1.2k Views Asked by At

What I have:

my class:

public class MyImage
{
    public String ImagePath { get; private set; }
    public String Name { get; private set; }

    // ...
}

XAML:

<Window.Resources>
    <DataTemplate x:Key="template_image">
        <Image Source="{Binding Path=ImagePath}" Stretch="None" />
    </DataTemplate>
    <DataTemplate x:Key="template_name">
        <TextBlock Text="{Binding Path=Name}" />
    </DataTemplate>
</Window.Resources>


<ListView x:Name="gui_listview_graphics" Margin="75,0,0,0">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Graphic" CellTemplate="{StaticResource template_image}" />
            <GridViewColumn Header="Name" CellTemplate="{StaticResource template_name}" />
        </GridView>
    </ListView.View>
</ListView>

Works fine.

Now what i now want..

I need to display an Image-List instead of just one Image.

my new class:

public class MyNewImage
{
    public ObservableCollection<String> ImagePath { get; private set; }
    public String Name { get; private set; }

    // ...
}

The DataTemplate should contain an Stackpanel which contains all images..

Is it possible?

If yes, how ..

Thank you!

2

There are 2 best solutions below

0
On BEST ANSWER

This template should work:

<DataTemplate x:Key="template_image_list">
  <ItemsControl ItemsSource="{Binding ImagePath}">
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel />
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <Image Source="{Binding}"></Image>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</DataTemplate>

Because a StackPanel does not have a property ItemsSource, you cannot bind directly to it. If you use it as ItemsPanelTemplate of an ItemsControl everything is fine.

0
On

In your DataTemplate include an ItemsControl whose Items property is bound to your collection of image paths. Your ItemTemplate for the ItemsControl will essentially be the same as your current DateTemplate, except you will use an implicit Binding for the Image source, since the string itself is your object. The default template for the ItemsPanel for an ItemsControl is a StackPanel already, but you can change this if necessary by setting the ItemsPanel property.