在FileSystemWatcher事件后更新Wpf图像

本文关键字:Wpf 图像 更新 FileSystemWatcher 事件 | 更新日期: 2023-09-27 18:18:58

我试图通过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"/>

在FileSystemWatcher事件后更新Wpf图像

您需要调用b.Freeze()(在创建它的线程上)以使其可供其他线程使用。