创建多个 .xaml 视图 [英] Creating multiple .xaml Views

查看:29
本文介绍了创建多个 .xaml 视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建名为 view.xaml 的 .xaml UserControl 的多个实例,它驻留在程序集 dir1asm.dlldir2asm 中.dllasm.dll 是同一个程序集,只是版本号和 view.xaml 的实现不同.

I want to create multiple instances of a .xaml UserControl named view.xaml, which resides in an assembly dir1asm.dll and dir2asm.dll whereas asm.dll is the same assembly that only differs in its version number and the implementation of view.xaml.

我有以下设置:

public void TestCreation() {

    Assembly asm = null;

    asm = Assembly.LoadFile("dir1asm.dll");
    CreateView(asm); // works!

    asm = Assembly.LoadFile("dir2asm.dll");
    CreateView(asm); // works!

    asm = Assembly.LoadFile("dir1asm.dll");
    CreateView(asm); // FAILS!

}

public void CreateView(Assembly assembly)
    {
        Type type = assembly.GetTypes().First<Type>(t => t.Name.Equals("View"));

        UserControl view = (UserControl)assembly.CreateInstance(type.FullName, false, BindingFlags.CreateInstance, null, new object[] { }, null, null);
    }

我收到以下异常:

带有异常详细信息

我能够在我的 view.xaml 的 InitializeComponent() 方法中将问题跟踪到这个位置:

I was able to track the problem up to this location in the InitializeComponent() method of my view.xaml:

尤其是在 InitializeComponent() 中:

and more specificially within InitializeComponent():

推荐答案

在这个问题上苦苦挣扎一周后,我终于找到了问题的原因和解决方案.

After a week suffering and laboring with this issue, I finally found both the reason for the problem and its solution.

问题出在自动生成的 *.gics 文件中,该文件由 UserControlInitializeComponent() 方法调用,如下图所示:

The problem lies within the auto-generated *.g.i.cs file, which is called by the InitializeComponent() method of a UserControl, as seen by the following:

此文件生成一个字符串(资源定位符),表示该 xaml 组件的路径,如下所示:

This file generates a string (a Resource Locator) that expresses the path to that xaml-component, as seen by the following:

现在,如果您有同一程序集的多个版本,并且两个版本都包含相同的 xaml 文件,WPF 不知道要实例化哪个 xaml 文件,因为资源定位器仅引用程序集的名称,而不引用其版本.

Now, if you have multiple versions of the same assembly and both versions include the same xaml-file, WPF does not know what xaml-file to instantiate, because the Resource Locator only references the name of the assembly but not its version.

这会导致 TargetInvocationException,即

{"组件 'MyNamespace.MyUserControl' 没有由 URI '/MyAssembly;comoponent/myusercontrol.xaml' 标识的资源"}

{"The component 'MyNamespace.MyUserControl' does not have a resource identified by the URI '/MyAssembly;comoponent/myusercontrol.xaml'"}

如下:

对此的简单(但绝对不明显)解决方案是将程序集版本添加到此资源定位器.这可以通过添加 -tag 修改项目的构建文件来实现,如下所示:

The simple (but most definitely not obvious) solution for this is to add the version of the assembly to this Resource Locator. This can be achieved by modifying the build-file of the project by adding the <AssemblyVersion>-tag as follows:

此致谢:

这篇关于创建多个 .xaml 视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆