I have a WPF-application that is looking for new images in a database and if something comes up, it adds the image into a list. When that event is raised I want it to add the image into a StackPanel.
First I tried just to insert the image, but got an InvalidOperationException saying "The calling thread must be STA, because many UI components require this." and came up with:
public void Instance_GraphicChanged(object sender, PropertyChangedEventArgs e)
{
foreach (Model.Graphic item in Model.IncomingCall.Instance.Graphics)
{
if(!_strings.Contains(item.ImageId.ToString()))
{
Thread thread = new Thread( new ThreadStart(
delegate()
{
//sp_images StackPanel for Images
sp_images.Dispatcher.Invoke(
DispatcherPriority.Normal, new Action(
delegate()
{
Image img = new Image();
img.Source = item.ImageObj; //ImageObj returns a BitmapImage
sp_images.Children.Add(img);
}
));
}
));
_strings.Add(item.ImageId.ToString());
}
}
}
This does not throw any kind of exception, but actually nothing happens...
Dispatcher. Instead, you should callsp_images.Dispatcher.BeginInvoke(...)with a delegate. Also, have you tried binding the image generation to anItemsControl? You can use a template to turn that into aStackPaneland just work withBitmapImageobjects contained within anObservableCollection.