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…
In reference to my comment, you could try something like this:
XAML
Code Behind
This should bypass any cross-thread exceptions you might have had before. It should also allow you to easily add new images to the
ObservableCollection, which will automatically update the UI with images. Also, the use of theItemTemplatemeans you don’t have to actually build the UI every time yourself; WPF will handle this for you.See here for more information on using the
ObservableCollection. Also, refer to this StackOverflow question for an explanation on the container templating.