繁体   English   中英

FileSystemWatcher事件后更新Wpf图像

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM