将TextBlock绑定到WPF应用程序中的日志文件

时间:2017-08-21 04:18:23

标签: c# wpf

我有一个将日志输出到日志文件的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)
        {

        }

    }
}

1 个答案:

答案 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