簡體   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