我在XAML资源词典中有很多<conv:[ConverterName] x:Key="[ConverterName]"/>
条目,每次密钥都与类型名称匹配。
有没有办法让密钥自动从类型中取名,类似于nameof
?除了方便之外,我希望代码更加重构。
答案 0 :(得分:2)
在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));
}
}
}