Flynn1179
Flynn1179

Reputation: 12075

Any way to set a ResourceDictionary key to match the class name?

I've got quite a few <conv:[ConverterName] x:Key="[ConverterName]"/> entries in XAML resource dictionaries, and every time the key matches the type name.

Is there any way to have the key take the name from the type automatically, similar to nameof? Aside from convenience, I'd like the code to be a bit more refactorproof.

Upvotes: 3

Views: 177

Answers (1)

mm8
mm8

Reputation: 169200

There is no way to do this in XAML but you can do it programmatically using reflection. Something like this:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        //get all types that implements from all assemlies in the AppDomain
        foreach(var converterType in AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(a => a.GetExportedTypes())
            .Where(t => typeof(IValueConverter).IsAssignableFrom(t) 
                && !t.IsAbstract 
                && !t.IsInterface))
        {
            //...and add them as resources to <Application.Resources>:
            Current.Resources.Add(converterType.Name, Activator.CreateInstance(converterType));
        }
    }
}

Upvotes: 2

Related Questions