Reputation: 1566
I am trying to load an image onto my WPF Window after it is received through a FileSystemEvent, however, I cannot access the image slot on the window because the FileSystemEvent happens on a different thread. I have read to use dispatchers and invoking, but nothing I try fixes the problem. Here is my code:
public MainWindow()
{
InitializeComponent();
if(!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = directory;
watcher.Filter = "*.jpg";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
BitmapImage b=new BitmapImage();
b.BeginInit();
b.UriSource=new Uri(e.FullPath);
b.EndInit();
image1.Dispatcher.Invoke(() => image1.Source = b); //What goes here?
//I have also tried Application.Current.Dispatcher.Invoke
}
And
<Image x:Name="image1" Grid.Row="0" Grid.Column="0"/>
Upvotes: 0
Views: 325
Reputation: 888077
You need to call b.Freeze()
(on the thread that created it) to make it available to other threads.
Upvotes: 1