2016-04-30 90 views
1

我試圖按照本教程:https://www.youtube.com/watch?v=6lVormV8cb8FileSystemWatcher的事件不觸發C#

但我FileSystemWatcher的事件似乎並沒有射擊。任何想法爲什麼?

ps。我對C#和Windows API的知識是非常原始的 - 請考慮任何迴應。

Window1.xaml.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 

using System.IO; 

namespace WpfApplication1 
{ 
    /// <summary> 
    /// Interaction logic for Window1.xaml 
    /// </summary> 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
     } 

     private void MainWindow_Loaded(object sender, RoutedEventArgs e) 
     { 
      string watchedFolder = System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Pictures"); 

      FileSystemWatcher fsw = new FileSystemWatcher(watchedFolder); 

      MainWindow.Title = "Monitoring: " + fsw.Path; 

      fsw.IncludeSubdirectories = true; 
      fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite; 

      fsw.Changed += new FileSystemEventHandler(fsw_Changed); 

      fsw.EnableRaisingEvents = true; 
     } 

     void fsw_Changed(object sender, FileSystemEventArgs e) 
     { 
      updatedImage.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, 
       new Action(
        delegate() 
        { 
         ImageSourceConverter isc = new ImageSourceConverter(); 
         updatedImage.Source = (ImageSource)isc.ConvertFromString(e.FullPath); 
        } 
       ) 
      ); 
     } 
    } 
} 

Window1.xaml

<Window x:Class="WpfApplication1.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:WpfApplication1" 
     mc:Ignorable="d" 
     Title="Window1" Height="350" Width="525" 
     Name="MainWindow"> 
    <Grid> 
     <Image Name="updatedImage" /> 

    </Grid> 
</Window> 

回答

1

看來你的XAML缺少關鍵的一塊。
MainWindow_Loaded事件處理程序的綁定。
沒有代碼綁定到該事件,因此沒有創建FileSystemWatcher並進行初始化。

<Window x:Class="WpfApplication1.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:WpfApplication1" 
     mc:Ignorable="d" 
     Title="Window1" Height="350" Width="525" 
     Name="MainWindow" 
     Loaded="MainWindow_Loaded"> 
+0

完美!謝謝! –