在WPF中的设计时查找启动程序集

时间:2009-06-07 23:47:56

标签: wpf

我有一个WPF MarkupExtension需要访问默认资源程序集中的资源。扩展在运行时工作正常,但在设计器中失败,因为扩展无法在启动程序集中找到默认资源。为了加载ResourceManager,我需要知道从哪个程序集加载资源。

在运行时,我可以通过在初始化时传递一个程序集来轻松处理 - 这很好用。

但是,在设计时,这个启动代码都没有执行,所以设计师炸弹并且无法加载页面。那么如何才能获得以下其中一项(不引用特定的应用程序类型):

  • 应用程序的启动程序集 (即WPF EXE)
  • 当前XAML文档标记扩展托管在

2 个答案:

答案 0 :(得分:2)

AFAIK,没有简单明了的方法......我使用以下方法查找具有入口点(即可执行程序集)的程序集,并包含从System.Windows派生的类。申请:

    public static Assembly GetEntryAssembly()
    {
        // Should work at runtime
        Assembly asm = Assembly.GetEntryAssembly();

        // Design time
        if (asm == null)
        {
            asm = (
                   from a in AppDomain.CurrentDomain.GetAssemblies()
                   where a.EntryPoint != null
                   && a.GetTypes().Any(t => t.IsSubclassOf(typeof(System.Windows.Application)))
                   select a
                  ).FirstOrDefault();
        }

        return asm;
    }

此代码需要针对特定​​需求进行调整(例如,它不适用于WPF控件库)

如果你想要检索XAML根元素,你可以在我前一段时间写的code of a markup extension中找到一些灵感。它通过在私有/内部字段上使用反射来查找根元素。

答案 1 :(得分:0)

Assembly.GetEntryAssembly.FullName将为您提供#1。对于你的其他问题,Assembly.GetExecutingAssembly不会这样做吗?