如何在 WPF 应用程序中使用 RichTextBox Target? 我不想有一个带有日志的单独窗口,我希望所有日志消息都输出在 WPF 对话框中的 richTextBox 中。
我尝试将 WindowsFormsHost 与 RichTextBox 框一起使用,但这对我不起作用:NLog 无论如何都打开了单独的 Windows 窗体。
最佳答案
同时,解决方法是使用可用的 3 个类 here ,然后按照以下步骤操作:
将 3 个文件导入到您的项目中
如果还没有这种情况,请使用
Project > Add Reference
添加对 WPF 程序集的引用:WindowsBase, PresentationCore, PresentationFramework
.在
WpfRichTextBoxTarget.cs
,将第 188-203 行替换为://this.TargetRichTextBox.Invoke(new DelSendTheMessageToRichTextBox(this.SendTheMessageToRichTextBox), new object[] { logMessage, matchingRule }); if (System.Windows.Application.Current.Dispatcher.CheckAccess() == false) { System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => { SendTheMessageToRichTextBox(logMessage, matchingRule); })); } else { SendTheMessageToRichTextBox(logMessage, matchingRule); } } private static Color GetColorFromString(string color, Brush defaultColor) { if (defaultColor == null) return Color.FromRgb(255, 255, 255); // This will set default background colour to white. if (color == "Empty") { return (Color)colorConverter.ConvertFrom(defaultColor); } return (Color)colorConverter.ConvertFromString(color); }
在您的代码中,配置新目标,如下例所示:
我希望它有所帮助,但它似乎绝对不是一个全面的实现......
public void loading() {
var target = new WpfRichTextBoxTarget();
target.Name = "console";
target.Layout = "${longdate:useUTC=true}|${level:uppercase=true}|${logger}::${message}";
target.ControlName = "rtbConsole"; // Name of the richtextbox control already on your window
target.FormName = "MonitorWindow"; // Name of your window where there is the richtextbox, but it seems it will not really be taken into account, the application mainwindow will be used instead.
target.AutoScroll = true;
target.MaxLines = 100000;
target.UseDefaultRowColoringRules = true;
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "console";
asyncWrapper.WrappedTarget = target;
SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);
}
关于wpf - 如何在 WPF 应用程序中使用 NLog 的 RichTextBox Target?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3705480/