所以我的表格显示我的 Application
Log
。
这是我的Log
模型:
public class LogEntry : IComparable<LogEntry>
{
public string DateTime { get; set; }
public int Index { get; set; }
public string Source { get; set; }
public Level Level { get; set; }
public string Message { get; set; }
public int CompareTo(LogEntry other)
{
return DateTime.CompareTo(other.DateTime);
}
}
public enum Level
{
All = 0,
Debug,
Info,
Warn,
Error,
Fatal,
Off
}
日志助手
这是我的LogHelper
类,它根据用户选择的级别添加当前LogEvent
:
public static class LogHelper
{
public static ObservableCollection<LogEntry> LogEntries { get; set; }
public static bool AddLogToList { get; set; }
private static int _level;
private static int _index;
private static string _formatPattern = "yyyy-MM-dd HH:mm:ss,fff";
public static void SetLevel(Level level)
{
_level = (int)level;
}
public static void AddLog(Level level, string message, string className, string methodName)
{
if (LogEntries == null)
LogEntries = new ObservableCollection<LogEntry>();
if (AddLogToList)
{
int levelValue = (int)level;
if (levelValue >= _level)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
if (LogEntries.Count == 1000)
LogEntries.RemoveAt(LogEntries.Count - 1);
LogEntry logEntry = new LogEntry()
{
DateTime = DateTime.Now.ToString(_formatPattern),
Index = _index++,
Level = level,
Source = className + "\" + methodName,
Message = message.Trim()
};
LogEntries.Insert(0, logEntry);
}));
}
}
}
}
所以我将LogEvent
添加到包含Ti 1000
条目的列表中。
现在,我希望能够过滤并显示我的唯一相关LogEvent
级别。
所以我添加了所有LogEvent
级别的ComboBox
,并订阅其SelectionChanged
事件:
private void cbLogLevel_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
int index = cbLogLevel.SelectedIndex;
LogHelper.SetLevel((Level)index);
lvLogger.ItemsSource = LogHelper.LogEntries.Where(m => m.Level == (Level)index).ToList();
}
所以在此SelectionChanged
事件之后,我可以看到相关的LogEvent
级别,但我唯一的问题是新的LogEvent
未显示。
也许我需要刷新我的收藏或其他东西?
您正在创建一个新的List<LogEntry>
,并将ItemsSource
属性设置为活动处理程序中的该属性。这意味着lvLogger
将不再连接到ObservableCollection
。
您可以过滤视图:
而不是重置ItemsSource
private void cbLogLevel_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
int index = cbLogLevel.SelectedIndex;
Level level = (Level)index;
LogHelper.SetLevel(level);
var collectionView = CollectionViewSource.GetDefaultView(lvLogger.ItemsSource);
collectionView.Filter = x =>
{
LogEntry logEntry = x as LogEntry;
return logEntry != null && logEntry.Level == level;
};
}