Behavior as a service in a WPF app.
Code highly inspired by DevExpress documentation.
- Create a new interface (ie:
IMyCustomService
) for your behavior that implementsIServiceBehavior
and expose whatever you want to expose. - Change the inheritance of an existing behavior from
Behavior<T>
toServiceBehavior<T>, IMyCustomService
. - Make sure your ViewModel implements
ISupportServices
. You can see an example in BaseViewModel.cs. - You can now call
GetService<IMyCustomService>()
from your ViewModel to get access to your service and call whatever is exposed.
When Services (derived from the ServiceBehavior
class) are registered in a View, they analyze their DataContext. If the DataContext is set to an ISupportServices
object, a service registers itself within this object. This is accomplished by calling the IServiceContainer.RegisterService
method on the ISupportServices.ServiceContainer
object. Thus, the service becomes available for use within the ISupportServices
object via the IServiceContainer.GetService<T>
method.
- You need to pass the
IServiceContainer
to sub-viewModels.