2013-08-16 48 views
0

我想将图像列表绑定到DataGrid.RowDetailsTemplate内部的stackpanel。 我的类结构如下:将图像列表绑定到StackPanel

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; } 
} 

在我的主类我有一个列表:

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

所有我想要做的就是在DataGridTextColumn显示元素的名称属性以及存储在RowDetails的Images属性中的所有图像。

我的XAML是:

<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> 

所有我能看到只是一个图片虽然有更多的一些存储在图像。有任何想法吗?

回答

0

好吧,所以这个问题的解决方案是使用ContentPresenter与转换器结合使用。

现在我的XAML看起来像这样:

<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> 

以及相应的转换器类:

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(); 
    } 
}