Home>

After each logging, I need to display the log in the ListView, and for this I created the Logs property in my ViewModel, but logging occurs in the Model

I have a so-so assumption on how to do this: make the Logs property static and access it in the place where I do the logging, but I understand that this is a bad idea because I will need to access Logs from another thread , which causes difficulties, besides that it seems wrong to me that I will have to change the ViewModel inside the Model. How can I organize this moment correctly?

class MainViewModel: BaseViewModel
{
   public ObservableCollection <
string >
 Logs {get; set; }
//code
}
class Scaner
{
   public async Task <
bool >
 Scan ()
   {
      FileLogger.Log ("Searching for new files ..."); //this text should be added to the Logs property of the ViewModel
      if (files.Count () >
 0)
      {
         FileLogger.Log ("Files found, sending to counterparty"); //this text should be added to the Logs property of the ViewModel
         //await any action
      }
      else
         FileLogger.Log ("Files not found"); //this text should be added to the Logs property of the ViewModel
   }
}

And there is xaml MainWindow

<
Window.DataContext >
   <
vm: MainViewMode >
<
/vm: MainViewModel >
<
/WindowDataContext >
<
ListView ItemsSource= "{Binding Logs}" >

Logging must be thread safe. That is, the logger itself must ensure the safety of logging wherever it is needed, whether it be a file or just an event call. If the ui needs to access the logger, the viewmodel needs to subscribe to events and synchronize the output to the ui using Progress , for example.

aepot2021-10-13 12:23:47

Please, glad I helped.

aepot2021-10-13 14:11:09