我有一个将日志输出到日志文件的wpf应用程序。正在写入日志文件。我想将日志文件的内容显示在UI上的textBlock
<TextBlock Style="{StaticResource LogViewStyle}"
Text="{Binding LogMessage,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"
x:Name="LogView" Foreground="White"
FontFamily="Consolas"
RenderTransformOrigin="0.415,0.382"
Grid.ColumnSpan="2" Margin="10,172,10,0"/>
代码如下所示。不知何故,TextBlock没有得到更新。我究竟做错了什么?
public partial class MainWindow : Window, INotifyPropertyChanged
{
static string configFile = "si_config.yaml";
static string logFilePath = "C:\\si_data\\logs\\";
NotifyIcon nIcon = new NotifyIcon();
public MainWindow()
{
InitializeComponent();
MyV V = ConfigFileManager.CreateTVFromConfigFile(configFile, logFilePath);
List<MyV> fV = ConfigFileManager.CreateFVFromConfigFile(configFile, logFilePath);
ReadFile(logFilePath + "ms_interface.log");
FVDataBinding.ItemsSource = fighterVehicles;
}
private string _fileText;
public string FileText {
get
{
return _fileText;
}
set {
if (string.Equals(value, _fileText))
return;
_fileText = value;
OnPropertyChanged("FileText");
}
}
public void ReadFile(string path)
{
FileText = File.ReadAllText(path);
OnPropertyChanged("FileText");
}
//INotifyPropertyChanged members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private void FVDataBinding_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
答案 0 :(得分:2)
绑定到FileText
属性:
<TextBlock Style="{StaticResource LogViewStyle}"
Text="{Binding FileText, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"
x:Name="LogView" Foreground="White"
FontFamily="Consolas"
RenderTransformOrigin="0.415,0.382"
Grid.ColumnSpan="2" Margin="10,172,10,0"/>
您在ReadFile
方法中设置了这个。没有名为LogMessage
的属性。
由于您明确指定了绑定的来源,因此您无需设置窗口的DataContext
。