![](/img/trans.png)
[英]FileSystemWatcher Fires Event After Second Change, But Not First
[英]Update Wpf Image after FileSystemWatcher Event
通過FileSystemEvent接收到圖像后,我試圖將圖像加載到WPF窗口中,但是,由於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()
(在創建它的線程上)以使其可用於其他線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.