大概這個代碼有味道。你確實混合了一個服務類和一個控件。最好做這樣的事情。在ILogger中定義事件及其參數類型: public interface ILogger Eventhandler NewUsageLogEntry; }
public class LogEventArgs : EventArgs
{
public LogEventArgs(string aMessage)
{
Message = aMessage;
}
public string Message { get; private set; }
}
視圖模型:
public class LogModeViewModel : ModeViewModel
{
public LogModeViewModel(ILogger aLogger)
{
if (aLogger == null)
{
throw new ArgumentNullException("aLogger", "Логгер не задан.");
}
Logger = aLogger;
Logger.NewUsageLogEntry += OnNewUsageLogEntry;
}
public ObservableCollection<ApplicationUsageLogEntry> LogMessages
{
get
{
if (mLogMessages == null)
{
mLogMessages = new ObservableCollection<ApplicationUsageLogEntry>();
}
return mLogMessages;
}
}
private ILogger Logger { get; set; }
private void OnNewUsageLogEntry(object aSender, LogEventArgs aEventArgs)
{
ApplicationUsageLogEntry lLogEntry = new ApplicationUsageLogEntry(aEventArgs.Message);
LogMessages.Add(lLogEntry);
}
private ObservableCollection<ApplicationUsageLogEntry> mLogMessages;
}
public class ApplicationUsageLogEntry
{
public ApplicationUsageLogEntry(string aMessage)
{
if (string.IsNullOrWhiteSpace(aMessage))
{
throw new ArgumentNullException("aMessage", "Сообщение не задано.");
}
Message = aMessage;
HappenOn = DateTime.Now;
}
public string Message { get; private set; }
public DateTime HappenOn { get; private set; }
public override string ToString()
{
string lResult = string.Format("{0:dd.MM.yyyy hh:mm:ss} | {1}", HappenOn, Message);
return lResult;
}
}
在我的代碼我使用一個DataGrid顯示日誌,但是你可以很容易地修改日誌消息是一個字符串。之後,您需要將此屬性綁定到您的TextBox.Text。小費:不要直接更新你的財產。更新一個私有的StringBuilder,然後將StringBuilder.ToString()的結果分配給LogMessages字符串屬性。