using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;
using NewLife.XCoder.Models;
namespace NewLife.XCoder.Controls;
/// <summary>彩色日志视图</summary>
/// <remarks>
/// 日志行是结构化数据,颜色由 <see cref="LogEntry.Kind"/> 决定;
/// 不再使用 RichTextBox 按关键词重新解析文本,因此追加、清空和自动滚动都更稳定。
/// </remarks>
public partial class LogView : UserControl
{
/// <summary>日志条目集合</summary>
public static readonly StyledProperty<IList<LogEntry>?> EntriesProperty =
AvaloniaProperty.Register<LogView, IList<LogEntry>?>(nameof(Entries));
/// <summary>是否自动滚动到底部</summary>
public static readonly StyledProperty<Boolean> AutoScrollProperty =
AvaloniaProperty.Register<LogView, Boolean>(nameof(AutoScroll), true);
private INotifyCollectionChanged? _observable;
private Boolean _scrollPending;
/// <summary>实例化彩色日志视图</summary>
public LogView()
{
InitializeComponent();
Items.ItemsSource = Entries;
}
/// <summary>日志条目集合</summary>
public IList<LogEntry>? Entries
{
get => GetValue(EntriesProperty);
set => SetValue(EntriesProperty, value);
}
/// <summary>是否自动滚动到底部</summary>
public Boolean AutoScroll
{
get => GetValue(AutoScrollProperty);
set => SetValue(AutoScrollProperty, value);
}
/// <summary>追加一条日志</summary>
/// <param name="entry">日志条目</param>
public void Append(LogEntry entry) => Entries?.Add(entry);
/// <summary>清空日志</summary>
public void Clear() => Entries?.Clear();
/// <inheritdoc />
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == EntriesProperty)
{
if (_observable != null) _observable.CollectionChanged -= OnCollectionChanged;
Items.ItemsSource = change.NewValue as IList<LogEntry>;
_observable = change.NewValue as INotifyCollectionChanged;
if (_observable != null) _observable.CollectionChanged += OnCollectionChanged;
ScrollToEnd();
}
else if (change.Property == AutoScrollProperty && AutoScroll)
{
ScrollToEnd();
}
}
private void OnCollectionChanged(Object? sender, NotifyCollectionChangedEventArgs e)
{
if (AutoScroll) ScrollToEnd();
}
private void ScrollToEnd()
{
if (_scrollPending) return;
_scrollPending = true;
Dispatcher.UIThread.Post(() =>
{
_scrollPending = false;
Scroll.ScrollToEnd();
}, DispatcherPriority.Background);
}
}
|