2015-06-24 6 views
0

Добавлены элементы управления изображением в WPF WrapPanel из списка изображений, определенных в xml. Все, кажется, на месте. Я даже проверял в отладке, но ничего не визуально. Есть ли у меня шаг?Динамически добавленное изображение для WrapPanel в WPF

 _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

Ваш код пропускает EndInit вызова после установки StreamSource свойства BitmapImage.

Кроме того, поток должен быть закрыт после загрузки растрового изображения, которое обычно делается с помощью using блока и который также требует, чтобы установить BitmapCacheOption.OnLoad:

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

В качестве альтернативы, BitmapImages также может быть загружена непосредственно из пути к файлам изображений без использования FileStream:

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

Вы можете также создать модель представления с коллекцией Объекты 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> 

См Data Templating Overview статьи на MSDN для деталей.

Смежные вопросы