c# - MVVM - 在 View 中显示来自多个模型实体的消息

标签 c# .net wpf logging mvvm

下午好

在我的项目中,我有一个包含 ListView 对象的 View 。现在我有一个名为 ControlUnit 的类(模型)需要向 View 报告其进度。大多数情况下,在给定时间会有多个 ControlUnit 对象。

例如,在我的 View 模型中,我将为列表中的每个 ControlUnit 对象调用一个 ControlUnit.DoWork(),当该工作完成时,我希望每个单元都向 ListView 添加一条消息,看起来像这样:“01/04/2015 16:00:00 - ControlUnit1 完成工作。”

我是 MVVM 的新手,实际上我正在改造一个旧的 winforms 应用程序,我在一段时间内回到 MVVM 作为练习的一种方式。在 WinForms 中,我刚刚引发了一个具有“消息”属性的事件,并在表单本身的代码中处理了该事件。

public class ControlUnit()
{
public string IpAddress {get;set;}
public string RootPassword {get;set;}

public void DoWork()
{
//Run some telnet commands
//Report result to View (in listview)
//Let's say I run a "uptime" command, I want to return the result of that command and display it in the listview in my view.
}
}

public class DataCollectorViewModel()
{
private List<ControlUnit> _unitList;

public void StartLogging()
{
_unitList.Add(new ControlUnit(IpAddress1,RootPassword1);
_unitList.Add(new ControlUnit(IpAddress2,RootPassword2);
_unitList.Add(new ControlUnit(IpAddress3,RootPassword3);

foreach (ControlUnit cu in _unitList)
{
cu.DoWork();
}

}

}

如有任何帮助,我们将不胜感激。

最佳答案

您需要创建一个对象来保存消息列表,然后将该对象传递给您想要显示消息的每个 View 模型。然后在您的 UI 中,您应该像这样绑定(bind)到消息列表:

public interface IMessageHandler
{
    void SendMessage(string msg);
}

public class MessageHandler : IMessageHandler
{
    public ObservableCollection<string> Messages { get; set; }
    public void SendMessage(string msg)
    {
        App.Current.Dispatcher.BeginInvoke(new Action(() => Messages.Add(msg)));
    }
}

public class ViewModel1 
{
    private readonly IMessageHandler _messageHandler;

    public ViewModel1(IMessageHandler messageHandler)
    {
        _messageHandler = messageHandler;
    }
}

public class ViewModel2 
{
    private readonly IMessageHandler _messageHandler;

    public ViewModel2(IMessageHandler messageHandler)
    {
        _messageHandler = messageHandler;
    }
}

您的主要应用程序 View 模型需要实例化 MessageHandler 类并传递它,以便每个人都有相同的实例。在您看来,您应该绑定(bind)到 Messages 集合。为了使其更加优雅,您还可以使用 IOC 容器。

关于c# - MVVM - 在 View 中显示来自多个模型实体的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28074139/

相关文章:

c# - 如何使用 Entity Framework 自动过滤掉软删除的实体?

c# - 如何使用 LINQ (C# 3.0) 更改 IDictionary 的内容

c# - Datagrid:如何获取 SelectedItem 的 CurrentCell?

c# - 简单的数据绑定(bind)不起作用

c# - 如何在 WPF 应用程序中配置 StructureMap?

c# - 模型绑定(bind)不适用于嵌套对象

javascript - 如何在 C# 中将 json 值转换为字典并使用字符串值来寻址它们?

c# - 枚举 Intellisense 显示属性?

c# - SaveFileDialog 阻止可移动驱动器

.net - 在实例化时赋予类唯一 ID : .Net