2015-06-19 13 views
0

裸露與我,因爲我對c#有點新。我已經構建了一個轉換器類,在其中傳遞文件路徑並返回文件的實際文本。如何使用FileSystemWatcher刷新正在從轉換器返回的文本

public class GetNotesFileFromPathConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var txtFilePath = (string)value; 
     FileInfo txtFile = new FileInfo(txtFilePath); 
     if (txtFile.Exists == false) 
      { 
       return String.Format(@"File not found"); 
      } 
     try 
     { 
      return File.ReadAllText(txtFilePath); 
     } 

      catch (Exception ex){ 
       return String.Format("Error: " + ex.ToString()); 
      } 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return null; 
    } 

該轉換器應用,像這樣的XAML:

 <TextBox x:Name="FilePath_Txt" > 
      <TextBox.Text> 
       <![CDATA[ 
       \\igtm.com\ART\GRAPHICS\TST\820777\0010187775\69352C5D5C5D195.txt 
       ]]> 
      </TextBox.Text> 
     </TextBox> 
     <TextBox x:Name="FilePathRead_Txt" Text="{Binding ElementName=FilePath_Txt,Path=Text,Converter={StaticResource GetNotesFileFromPathConverter},Mode=OneWay}" /> 

這是所有工作的罰款。但是,如果文本文件中的文本已更新,則不會反映在XAML中。我看過有關使用FileSystemWatcher的信息,但不知道如何將其應用於轉換器,以便更新返回的文本。誰能幫忙?

回答

1

我不會在這種情況下使用轉換器,因爲您需要在文件上設置FileSystemWatcher。我會將FilePath_Txt的Text綁定到視圖模型中的一個屬性,並將FilePathRead_Txt的Text綁定到另一個屬性。然後,您將更新FileSystemWatcher以查找此新文件的更新。如果文件名更改或文件更新,那麼您將使用您的轉換器中的邏輯來更新FilePathRead_Txt屬性。如果您不熟悉MVVM模式,請參閱此MSDN article

在您的視圖模型:

string filename; 
public string Filename 
{ 
    get {return filename;} 
    set { 
     if (filename != value) 
     { 
     filename = value; 
     OnNotifyPropertyChanged("Filename"); 
     WatchFile(); 
     UpdateFileText(); 
     } 
} 

string fileText; 
public string FileText 
{ 
    get {return fileText;} 
    set { 
     fileText = value; 
     OnNotifyPropertyChanged("FileText"); 
    } 
} 

private void WatchFile() 
{ 
    // Create FileSystemWatcher on filename 
    // Call UpdateFileText when file is changed 
} 

private void UpdateFileText() 
{ 
    // Code from your converter 
    // Set FileText 
} 

在XAML:

<TextBox x:Name="FilePath_Txt" Text="{Binding Filename, UpdateSourceTrigger=PropertyChanged}"/> 
<TextBox x:Name="FilePathRead_Txt" Text="{Binding FileText}" /> 
相關問題