Question

i want to bind a list of images to a stackpanel which is inside a DataGrid.RowDetailsTemplate. My class structure is as follows:

public class A
{
    private List<MyImage> _images = new List<MyImage>();
    public List<MyImage> Images { get; set; }
    public string Name { get; set; }

    public void AddImage(byte[] src) { ... }
}

public class MyImage
{
    public BitmapImage Image { get; set; }
    public byte[] RawData { get; set; }
}

In my main class i have a list of A:

public List<A> AList { get; set; }
dataGrid1.ItemsSource = AList;
dataGrid1.DataContext = AList;

All i want to do is to display the Name property of an element in a DataGridTextColumn and all images stored in the Images property in the RowDetails.

My xaml is:

<DataGrid name="dataGrid1">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Path=Name}"/>
    </DataGrid.Columns>
    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <StackPanel DataContext="{Binding Path=Images}">
                <Image Source="{Binding Path=RawData}"/>
            </StackPanel>
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>

All i get to see is just one image although there are some more stored in Images. Any ideas?

Était-ce utile?

La solution

Ok, so the solution of this problem was the use of ContentPresenter combined with a converter.

Now my XAML looks like this:

<DataGrid name="dataGrid1">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Path=Name}"/>
    </DataGrid.Columns>
    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Images, Converter={StaticResource ImageCollectionConverter}}"/>
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
</DataGrid>

And the corresponding converter class:

public class ImageCollectionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        List<MyImage> images = value as List<MyImage>;

        if (images != null)
        {
            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;

            foreach (DesignImage img in images)
            {
                Image image = new Image();
                image.Source = img.Image;

                stack.Children.Add(image);
            }

            return stack;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top