2015-06-24 51 views
0

從xml中定義的圖像列表中爲WPF WrapPanel添加了圖像控件。 一切似乎都已到位。我甚至在調試中檢查過,但沒有任何可視的。 有沒有我失蹤的一步?向WPF中的WrapPanel動態添加圖像

 _printImages.ReadXml(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Images.xml")); 

     if (_printImages.Tables.Contains("image") && _printImages.Tables["image"].Rows.Count > 0) 
     { 

      foreach (DataRow row in _printImages.Tables["image"].Rows) 
      { 
       // build info object 
       ImageInfo imgInfo = new ImageInfo(); 

       imgInfo.Source = row["Source"].ToString(); 
       imgInfo.Custom = bool.Parse(row["Custom"].ToString()); 
       imgInfo.Font = row["Font"].ToString(); 
       imgInfo.FontSize = int.Parse(row["FontSize"].ToString()); 
       imgInfo.CharacterLimit = int.Parse(row["Characterlimit"].ToString()); 
       imgInfo.CustomType = row["Customtype"].ToString(); 

       _images.Add(imgInfo); 

       //create control 
       Image imgControl = new Image(); 
       BitmapImage imgFile = new BitmapImage(); 

       try 
       { 
        imgFile.BeginInit(); 
        imgFile.StreamSource = new FileStream(imgInfo.Source, FileMode.Open); 
        imgControl.Source = imgFile; 
        imgControl.Tag = _images.Count - 1; 
        imgControl.Height = Properties.Settings.Default.ImageHeight; 
        imgControl.Width = Properties.Settings.Default.ImageWidth; 
        imgControl.MouseDown += new MouseButtonEventHandler(image_MouseDown); 
        imgControl.Visibility = System.Windows.Visibility.Visible; 
        imageSelectionPanel.Children.Add(imgControl); 
       } 

       catch (System.Exception ex) 
       { 
        MessageBox.Show(ex.Message.ToString(), "Unable to create image"); 
       } 


      } 
     } 

回答

0

你的代碼丟失設置的BitmapImage的StreamSource財產後EndInit電話。

using (var stream = new FileStream(imgInfo.Source, FileMode.Open)) 
{ 
    imgFile.BeginInit(); 
    imgFile.StreamSource = stream; 
    imgFile.CacheOption = BitmapCacheOption.OnLoad; 
    imgFile.EndInit(); 
} 

或者,BitmapImages也可以直接從所加載:

此外,流應該在加載位圖,這通常是由一個using塊完成,這也需要設置BitmapCacheOption.OnLoad後關閉

var imgFile = new BitmapImage(new Uri(imgInfo.Source, UriKind.RelativeOrAbsolute)); 

你也可以創建一個視圖模型的集合:不使用一個FileStream圖像文件路徑ImageInfo對象並將一個ItemsControl綁定到這個集合。 ItemsControl的將有WrapPanel作爲其ItemsPanel,和一個ItemTemplate與圖像控制:

<ItemsControl ItemsSource="{Binding ImageInfos}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel/> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Image Source="{Binding Source}"/> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

參閱MSDN上的Data Templating Overview文章的詳細信息。