MarkupExtension.ProvideValue -- Is the IServiceProvider actually used?
Asked Answered
P

2

6

I was going through some old code of mine and came across a hybrid IValueConverter / MarkupExtension class. It got me wondering if the IServiceProvider in the ProvideValue method was actually useful, and how it would be useful?

I see that IServiceProvider only has one method: GetService, which must be cast to the proper service type. I also looked at the MarkupExtension.ProvideValue MSDN page and it lists different types of services. I guess, I'm just wondering if any of those services are useful or should I just leave my method as it is?

Current Method:

public Object ProvideValue(IServiceProvider serviceProvider)
{
    return new MyConverter();
}

Basically, should I do the following:

public Object ProvideValue(IServiceProvider serviceProvider)
{
    var provider = serviceProvider as SomeType;

    if (provider == null) return new MyConverter();

    //Do something with the provider here?
}
Paralytic answered 14/9, 2011 at 22:1 Comment(0)
A
6

If your MarkupExtension works without neeeding any interaction with the IServiceProvider then obviously there's nothing to be gained from accessing it. All MarkupExtension/ValueConverter combos I 've seen and written myself also fall into this category.

Moving on from practical matters, if you are just looking for reading material there's more information on what services the provider can make available and how they might be useful here.

Aniconic answered 14/9, 2011 at 22:7 Comment(0)
C
16

The provider can be useful to get information on the target object and property which it is being applied to for example. If you don't need to know these values then you don't need to use it

Example

public override object ProvideValue(IServiceProvider provider)
{
    IProvideValueTarget service = (IProvideValueTarget)provider.GetService(typeof(IProvideValueTarget));
    DependencyObject targetObject = service.TargetObject as DependencyObject;
    DependencyProperty targetProperty = service.TargetProperty as DependencyProperty;

    // ...
}
Collegiate answered 14/9, 2011 at 22:36 Comment(0)
A
6

If your MarkupExtension works without neeeding any interaction with the IServiceProvider then obviously there's nothing to be gained from accessing it. All MarkupExtension/ValueConverter combos I 've seen and written myself also fall into this category.

Moving on from practical matters, if you are just looking for reading material there's more information on what services the provider can make available and how they might be useful here.

Aniconic answered 14/9, 2011 at 22:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.