在 FileSystemWatcher 事件后更新 Wpf 图像
Update Wpf Image after FileSystemWatcher Event
我试图在通过 FileSystemEvent 接收图像后将图像加载到我的 WPF Window,但是,我无法访问 window 上的图像插槽,因为 FileSystemEvent 发生在不同的线。我已经阅读过使用调度程序和调用,但我没有尝试解决问题。这是我的代码:
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
}
和
<Image x:Name="image1" Grid.Row="0" Grid.Column="0"/>
您需要调用 b.Freeze()
(在创建它的线程上)以使其可供其他线程使用。
我试图在通过 FileSystemEvent 接收图像后将图像加载到我的 WPF Window,但是,我无法访问 window 上的图像插槽,因为 FileSystemEvent 发生在不同的线。我已经阅读过使用调度程序和调用,但我没有尝试解决问题。这是我的代码:
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
}
和
<Image x:Name="image1" Grid.Row="0" Grid.Column="0"/>
您需要调用 b.Freeze()
(在创建它的线程上)以使其可供其他线程使用。