How to pass Events from Model to ViewModel in WPF/C#? -
in class registered event external dll, raised when there changes on variables external code.
public class model { .... public void connect { .... client.onnotification += (s, e) => { this.onnotification(s,e); } } } and have viewmodel in want notified when event raised in class model.
public class viewmodel { ... // call method when event in class model raised public void dosomething() { } } any ideas clean , easy way that?
thank you.
solution 1: pass in client viewmodel's constructor , let viewmodel subscribe onnotification() (pass in interface if available)
solution 2: make model implement inotifypropertychanged if you're using mvvm; pass in interface viewmodel's constructor , subscribe propertychanged.
if you're not using mvvm, can use same methodology adding custom clientnotification event model, pass in entire model viewmodels constructor, , subscribe event.
solution 3: use messaging system (aka message bus) such prism's event aggregator class or mvvm light's messenger class, or write own.
edit: here's example using mvvm light: (note: coding memory, not tested)
add using reference galasoft.mvvmlight.messaging;
create small message class containing properties need. can inherit mvvm light's messagebase class if want not necessary.
public class clientnotificationmessage : messagebase { public string someproperty { get; set;} public int anotherproperty { get; set;} } in model's event handler, send message by:
client.onnotification += (s, e) => { var msg = new clientnotificationmessage() { ... }; messenger.default.send<clientnotificationmessage>(msg); } in viewmodel constructor, register receive messages by:
messenger.default.register<clientnotificationmessage>(this, msg => { // handle incoming clientnotificationmessage // if (msg.someproperty != ) ... }); i'm sure there other additional solutions other ppl can add.
Comments
Post a Comment