2017-07-03 79 views
0

我正在WPF應用程序中,我想要顯示一個圖標列表,我已經嵌入到png圖像到我的項目的資源文件夾中。
的圖像建設行動‘資源’,它們位於如下:Windows WPF迭代加載資源文件

'NameOfProject'/Resources/Icons/'SomeCategories'/'AllTheIcons'.png 

由於大約有一千個我想通過一個foreach語句將它們加載到ListView中,像這樣:

foreach (imageorwhatever icon in Resources/Icons/Category1) { ... } 
foreach (imageorwhatever icon in Resources/Icons/Category2) { ... } 
etc. 

我到目前爲止還沒有找到一種方法來實現這一目標。我找到的所有解決方案均單獨針對每個資源,或從文件加載它們。

我寧願反覆加載圖像,因爲我真的不希望在代碼或XAML

回答

0

使用它們WPF他們需要ResourceDictionary中的一部分,所以他們都可以訪問定義1000倍的圖像。下面是一些代碼,爲我的作品:

using System; 
using System.IO; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Media.Imaging; 

namespace ResourceTest 
{ 
    public partial class MainWindow 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 

      var dict = new ResourceDictionary(); 

      var baseDir = AppDomain.CurrentDomain.BaseDirectory; 

      foreach (var file in Directory.GetFiles("Images")) 
      { 
       dict.Add(file, new BitmapImage(new Uri(Path.Combine(baseDir, file)))); 
      } 

      Application.Current.Resources.MergedDictionaries.Add(dict); 

      foreach (var file in Directory.GetFiles("Images")) 
      { 
       var img = new Image(); 
       img.Source = (BitmapImage) FindResource(file); 

       ListBox.Items.Add(img); 
      } 
     } 
    } 
} 

所有你需要的是在你的XAML命名爲「列表框」來運行這個列表框:

<ListBox x:Name="ListBox" HorizontalAlignment="Left" Height="238" Margin="23,30,0,0" VerticalAlignment="Top" Width="130"/> 

我沒有花長在這,而是的第二個循環會更好,只是將項目放入List中,然後分配給ResourceDictionary和ListBox,但這是有效的。

編輯:忘了,但我只是使文件名,你可以在上面的例子中看到的資源的名稱。可能要更改或至少刪除擴展名。