开发者

C#,WPF Subscribing for an external event in code-behind

开发者 https://www.devze.com 2023-03-08 09:30 出处:网络
I\'m trying to subscribe for an event in an external class using code-behind in WPF and I obviously fail.

I'm trying to subscribe for an event in an external class using code-behind in WPF and I obviously fail.

I have an external library which uses ActiveMQ.NMS API to communicate with a broker and asynchronously listen on a topic. To do the second we need to register to an event called consumer.Listener. Everything worked perfect until creating a WPF project referencing the library and tryin开发者_JS百科g to subscribe to the event from code-behind (in code behind I called instance of an object responsible for communicating with the broker, created the handler and registered it).

As I understand now the reason behind my problem is Thread Affinity, however I would still love to know how to do what I was trying to do from code-behind even though most developers will immediately despise me for even thinking about such a thing. As a side note: it's a bit funny that debugger without giving any reason just skips some lines in methods if it feels like doing that.

Also, what is the recommended pattern for dealing with external events in WPF?

Thank you for your feedback :)


I'm going to assume that when you say "external events" you simply mean public events, exposed by an object of some kind. However you use the term external when referring to the library which uses ActiveMQ.NMS API... so I assume in that context you mean that it's a library outside of your code base, something you import, reference etc. Please correct / edit your post if I'm misunderstanding.

Assuming "consumer" is an object inside the library you reference with your project, once you instantiate "consumer", you should have a piece of code that looks something like:

consumer.Listener += new WhateverTheHandlerEventArgsIsCalledHere(consumer_Listener);

After you finish typing in "new" the intellisense should fill out the rest for you automatically if you hit the tab key twice.

I don't know why you think most developers would despise you for thinking about that... it's usually a good practice.

0

精彩评论

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