c# - 有什么方法可以设置 ResourceDictionary 键以匹配类名?
问题描述
我<conv:[ConverterName] x:Key="[ConverterName]"/>
在 XAML 资源字典中有很多条目,并且每次键都与类型名称匹配。
有没有办法让密钥自动从类型中获取名称,类似于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));
}
}
}
推荐阅读
- android - 如何在 Kotlin 的卡片视图中设置属性
- python - 使用 PIL(LOW) 绘制重叠的轮廓文本
- c# - 无法在 Excel 单元格中输入“空”文本
- xml - 有什么方法可以运行 XSLT 并使用 Apache fop 在线生成 PDF?
- java - 如何激活具有多个条件的 Eclipse UI 处理程序
- office-js - 如何使用 Office-js API 使自定义 Word-Addin 检查拼写错误
- c++ - 函数返回的类的析构函数
- android - 如何从 Facebook 帐户工具包中获取用户输入的号码?
- node.js - 我无法访问此文件名 [{"filename":"54526108_1946746692102415_4003062236024143872_n.jpg"}]
- javascript - 如何将字符串转换为 mongodb ObjectId?