I have built a converter class where you pass in a file path and it returns the actual text of the file.
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;
}
The converter is applied like so in the 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}" />
This is all working fine. However, if the text in the text file is updated, it is not reflected in the XAML. I've seen information on using the FileSystemWatcher, but am not sure how to apply it inside of a converter so that the text being returned is updated. can anyone help?
I wouldn't use a converter in this case since you'll need to setup a
FileSystemWatcher
on the file. I would bind theText
of FilePath_Txt to a property in your view model and bind theText
of FilePathRead_Txt to another property. You would then update theFileSystemWatcher
to look for updates to this new file. If the filename changes or the file is updated then you would use the logic you had in your converter to update the FilePathRead_Txt property. If you aren't familiar with the MVVM pattern, take a look at this MSDN article.In your view model:
In XAML: