在WPF中将图像动态添加到WrapPanel
从xml中定义的图像列表向WPF WrapPanel添加了图像控件。 一切似乎都准备好了。我甚至在调试中进行了检查,但没有任何内容是可视的。 有没有我错过的一步在WPF中将图像动态添加到WrapPanel,wpf,dynamic,wrappanel,Wpf,Dynamic,Wrappanel,从xml中定义的图像列表向WPF WrapPanel添加了图像控件。 一切似乎都准备好了。我甚至在调试中进行了检查,但没有任何内容是可视的。 有没有我错过的一步 _printImages.ReadXml(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Images.xml")); if (_printImages.Tables.Contains("image") &&
_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
调用
此外,加载位图后应关闭流,这通常由使用
块完成,并且还需要设置位图缓存选项。OnLoad
:
using (var stream = new FileStream(imgInfo.Source, FileMode.Open))
{
imgFile.BeginInit();
imgFile.StreamSource = stream;
imgFile.CacheOption = BitmapCacheOption.OnLoad;
imgFile.EndInit();
}
或者,也可以直接从图像文件路径加载位图图像,而无需使用文件流:
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>
有关详细信息,请参阅MSDN上的文章