向WPF中的WrapPanel动态添加图像

问题描述:

从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"); 
       } 


      } 
     } 

你的代码丢失设置的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文章的详细信息。