首页 > 解决方案 > 有什么方法可以设置 ResourceDictionary 键以匹配类名?

问题描述

<conv:[ConverterName] x:Key="[ConverterName]"/>在 XAML 资源字典中有很多条目,并且每次键都与类型名称匹配。

有没有办法让密钥自动从类型中获取名称,类似于nameof?除了方便之外,我还希望代码能够更易于重构。

标签: c#wpfxamlresourcedictionary

解决方案


在 XAML 中无法执行此操作,但您可以使用反射以编程方式执行此操作。像这样的东西:

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));
        }
    }
}

推荐阅读