Since I needed to solve a similar conundrum I gave it some though and this is what I came up: you can do this with binding instead of an event, I would use a service to get the messages, this is different than your WCF service, a service in MVVM is a class that does things for the ViewModel, this way the ViewModel doesn’t need to know how the messages get to it, they just do, lets’ see some code:
The WCF service:
public class MessagesWFCService : IMessagesWFCService
{
public void SendMessage(string message)
{
MessageService.Instance.AddMessage(message);
}
}
The service:
public interface IMessageService
{
void AddMessage(string message);
}
public class MessageService : IMessageService
{
private static MessageService _Instance = null;
private MessageViewModel _MessageViewModel = null;
private ServiceHost _ServiceHost = null;
public MessageService()
{
_Instance = this;
_ServiceHost = new ServiceHost(typeof(MessagesWFCService));
}
public void AddMessage(string message)
{
_MessageViewModel.Messages.Add(message);
}
public void Close()
{
_ServiceHost.Close();
}
public static MessageService Instance
{
get
{
return _Instance;
}
set
{
if(_Instance != value)
_Instance = value;
}
}
public MessageViewModel MessageViewModel
{
get
{
return _MessageViewModel;
}
set
{
if(_MessageViewModel != value)
_MessageViewModel = value;
}
}
public void Open()
{
_ServiceHost.Open();
}
}
The ViewModel
public class MessageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<string> _Messages = null;
private IMessageService _MessageService = null;
public MessageViewModel()
{
_MessageService = new MessageService();
_MessageService.MessageViewModel = this;
_MessageService.Open();
}
public ObservableCollection<string> Messages
{
get
{
return _Messages;
}
set
{
if(_Messages != value)
{
_Messages = value;
PropertyChangedEventHandler eventHandler = PropertyChanged;
if(eventHandler != null)
eventHandler(this, new PropertyChangedEventArgs("Messages"));
}
}
}
}
Of course you’ll need to set the view’s DataContext to the ViewModel and bind the ItemsSource property of the control to the ViewModel’s Messages property.
If you are using
Prism or Unity you should use the Container to resolve the MessageService instead of creating the instance directly.
Take a look, keep in mind that I haven’t tested this yet, but I will, and I think it can give you some guidance.