我已经构建了一个转换器类,您可以在其中传递一个文件路径,它返回文件的实际文本。
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的信息,但不知道如何在转换器中应用它,以便更新要返回的文本。有人能帮忙吗?
发布于 2015-06-19 22:16:47
在这种情况下,我不会使用转换器,因为您需要在文件上设置一个FileSystemWatcher。我将将Text of FilePath_Txt绑定到视图模型中的属性,并将Text of FilePathRead_Txt绑定到另一个属性。然后更新FileSystemWatcher以查找这个新文件的更新。如果文件名更改或文件被更新,那么您将使用转换器中的逻辑来更新FilePathRead_Txt属性。如果您不熟悉MVVM模式,请看一下这个MSDN文章。
在您看来,模型:
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}" />https://stackoverflow.com/questions/30947760
复制相似问题