2016-04-30 75 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

完美!谢谢! –