开发者

events between unrelated classes

开发者 https://www.devze.com 2023-03-19 13:21 出处:网络
I have class A that is data context of my main window. I have class B that is view model of one of the windows of the application.

I have class A that is data context of my main window. I have class B that is view model of one of the windows of the application. No relation between the classes.

I need somehow to raise an event in class B , while the event handler is located in class A.

Is it possible to do so ?

Example of what I am doing is: I am tring to change the main window 开发者_StackOverflowTitle from class B.

Thanks for help


In my book you should be looking at messenger / event aggregator for pub/sub. PRISM comes with one, so do things like the MVVM Light toolkit, or you can grab my own "drop in cs file" one from Github - TinyMessenger.

This allows decoupled communication - the only thing the publisher and subscriber have in common is the aggregator and the message format itself. If the classes are unrelated, and probably constructed separately, you shouldn't be coupling them with an event. If you do use an event you need to be aware of the GC implications of subscribing to an event, if the lifetimes of the two classes are expected to be different.

So, in a very simple example, in class A you'd do something like

this.messenger.Subscribe<TitleChangeMessage>(m => <do some stuff>);

Then in class B, whenever you want to fire the "event" you'd do:

this.messenger.Publish(new TitleChangedMessage("new title"));


You just need to make the event in class B public and attach a delegate from class A to it. Here is an example: B's constructor starts a background task, which waits for 2 secs and then raises the event. A's constructor creates an object b of type B and attaches its delegate to b's event. In the main function an object of class A is created and then the thread is put to sleep for 5 sec. Before that time passes the event has already been fired and handled.

    class A
    {
        private B b;

        public A()
        {
            b = new B();
            b.MyEvent += MyHandler;
        }

        public void MyHandler(string s)
        {
        }

        public static void Main(string[] args)
        {
            A a = new A();

            Thread.Sleep(5000);
        }
    }

    class B
    {
        public B()
        {
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(2000);
                MyEvent("");
            });
        }

        public delegate void MyDelegate(string s);
        public event MyDelegate MyEvent;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号