0

我想将我的日志写入 ViewModel,这样我就可以向用户公开日志。

首先我将 View 绑定到 ViewModel

<TextBox Grid.Row="1" TextWrapping="Wrap" Text="{Binding Logger}" AcceptsReturn="True" IsReadOnly="True"
                 ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto"/>

这是视图模型

private string logger;

public string Logger
{
    get { return logger; }
    set
    {
        logger = value;
        this.RaisePropertyChanged("Logger");
    }
}

然后,我创建了实现 ILoggerFacade 的客户记录器类,并覆盖了 Bootstrapper 中的 CreateLogger 方法。

在引导程序中

protected override ILoggerFacade CreateLogger()
    {
        return new MainLogger();
    }

在客户记录器类中

public class MainLogger : ILoggerFacade
{
    public void Log(string message, Category category, Priority priority)
    {
        string messageToLog = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{1}: {2}. Priority: {3}. Timestamp:{0:u}.", DateTime.Now, category.ToString().ToUpper(System.Globalization.CultureInfo.InvariantCulture), message, priority.ToString());
        //////??????//////
    }
}

应该填写什么???????。我试过Import IEventAggregator发布数据到ViewModel,这里直接导入ViewModel。两者都不起作用,因为在注册容器之前调用了 CreatorLogger 方法。那么如何将日志写入 ViewModel 呢?

4

1 回答 1

1

记录器应该简单地保存日志消息并将其公开在一个属性中:

公共接口 IMainLogger : ILoggerFacade { List Messages { get; } }

public class MainLogger : IMainLogger
{
    public MainLogger()
    {
        Messages = new ObservableCollection<string>();
    }

    public ObservableCollection<string> Messages { get; private set; }

    public void Log(string message, Category category, Priority priority)
    {
        string messageToLog = ...;
        Messages.Add(messageToLog);
    }
}

这基本上就是记录器应该做的:记录消息。现在您想在某个 TextBox 中显示它,该 TextBox 包含在您注入到区域中的 View 中,对吧?为此,您需要通过构造函数依赖注入将该记录器传递给该区域视图的模块。我正在使用 MEF,所以我不太确定如何使用 Unity 进行操作,但是当您在代码中配置容器时,它可能看起来像这样:

container.RegisterType<IMainLogger, MainLogger>(new ContainerControlledLifetimeManager());
container.RegisterType<ContainingTextBoxModule>(new InjectionConstructor(container.Resolve<IMainLogger>()));

模块获取并公开记录器的位置:

public class ContainingTextBoxModule : IModule
{    
    public IMainLogger Logger { get; private set; }

    public ContainingTextBoxModule(IMainLogger logger)
    {
        Logger = logger;
    }
}

然后,您的模块的 ViewModel 可以中继消息,您可以从您的视图绑定到它/它们。

这回答了你的问题了吗?

于 2013-05-17T09:34:37.087 回答