【发布时间】:2018-03-28 12:50:00
【问题描述】:
所以我有表格显示我的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 添加到包含最多1000 条目的列表中。
现在我希望能够过滤并显示我唯一的相关LogEvent 级别。
所以我添加了ComboBox 和我所有的LogEvent 级别并订阅了它的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 没有显示。
也许我需要刷新我的收藏或其他东西?
【问题讨论】:
-
我建议你调查listcollectionview和过滤。以您的 observablecollection 为基础的 listcollectionview 并添加一个过滤器来比较项目的级别和您选择的级别。过滤器可以设置为谓词。 social.technet.microsoft.com/wiki/contents/articles/…
标签: wpf collections