有什么方法可以设置 ResourceDictionary 键以匹配 class 名称?
Any way to set a ResourceDictionary key to match the class name?
我在 XAML 资源字典中有很多 <conv:[ConverterName] x:Key="[ConverterName]"/>
条目,每次键都与类型名称匹配。
有没有办法让键自动从类型中获取名称,类似于nameof
?除了方便之外,我还希望代码更能防止重构。
在 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));
}
}
}
我在 XAML 资源字典中有很多 <conv:[ConverterName] x:Key="[ConverterName]"/>
条目,每次键都与类型名称匹配。
有没有办法让键自动从类型中获取名称,类似于nameof
?除了方便之外,我还希望代码更能防止重构。
在 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));
}
}
}