2016-01-01 30 views
0

我想給folder path並從該文件夾的路徑如果folder contains 3 images我想display those 3 imagesStackPanel WPF Form如何從文件夾中添加StackPanel WPF中的多個圖像?

我試過類似下面的正常工作爲一個圖像,而是如何能夠加載所有從給定文件夾中的圖片?

<Window x:Class="wpfBug.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded"> 
    <StackPanel Name="sp"> 
    </StackPanel> 
</Window> 



private void Window_Loaded(object sender, RoutedEventArgs e) 
     { 
      Image i = new Image(); 
      BitmapImage src = new BitmapImage(); 
      src.BeginInit(); 
      src.UriSource = new Uri("mypic.png", UriKind.Relative); 
      // how to load all images from given folder? 
      src.EndInit(); 
      i.Source = src; 
      i.Stretch = Stretch.Uniform; 
      //int q = src.PixelHeight;  // Image loads here 
      sp.Children.Add(i); 
     } 

回答

2

您應該使用ItemsControl,如下所示。它使用垂直的StackPanel作爲其項目的默認面板。

<ItemsControl x:Name="imageItems"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Image Source="{Binding}" Margin="5"/> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

設置的ItemsControl的ItemsSource這樣的:

imageItems.ItemsSource = Directory.EnumerateFiles(FOLDERPATH, "*.png"); 

從路徑字符串到ImageSource的轉換由執行內置在WPF類型轉換。


您可以使用不同的ItemsPanel這樣的:

<ItemsControl ...> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <StackPanel Orientation="Horizontal"/> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    ... 
</ItemsControl> 
+0

我認爲所有的圖像都彼此loasing :( 我怎樣才能使一個空間兩個圖像之間 – Neo

+1

設置其保證金的財產? 。 – Clemens

+0

仍然只顯示一個圖像:O奇怪我已經寫了'imageItems.ItemsSource = Directory.EnumerateFiles(FOLDERPATH,「* .png」);'on'Window_Loaded' – Neo

相關問題