使用MEF对照XAML的实例化 [英] Using MEF in controls instantiated from XAML

查看:287
本文介绍了使用MEF对照XAML的实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我已经创建了进口使用 [导入] 属性几个部分的用户控件。

I have a UserControl I've created which imports several parts using the [Import] attribute.

public class MyUserControl : UserControl, IPartImportsSatisfiedNotification
{
    [Import]
    public IService Service { get; set; }

    public MyUserControl()
    {
    }

    public void OnImportsSatisfied()
    {
        // Do something with Service.
    }
}

该用户控件的XAML实例化,所以其进口不被满足, OnImportsSatisfied 不会被调用。

This UserControl is instantiated from XAML, so its imports aren't being satisfied and OnImportsSatisfied isn't being called.

<local:MyUserControl />

我的问题是我怎么能满足我的类进口时,它正在创建XAML

My question is how can I satisfy my class's imports when it's being created in XAML.

推荐答案

从MSDN:

要被实例化作为XAML对象元素,定制类必须   符合下列要求:
      自定义类必须是公共的,必须公开一个默认的(无参数)公共构造函数。 (请参见下面的部分注意事项   关于结构。)
      自定义类不能是嵌套类。在全名路径额外的点,使类的命名空间划分不明确,以及   干扰其他XAML的功能,如附加属性。
  如果一个对象可以被实例化为对象元素,创建的对象   可以填补该采取的任何属性的属性元素形式   对象作为其基本类型。
  您仍可以提供对象值   对各类不符合这些标准,如果启用一个值   转换器。欲了解更多信息,请参阅类型转换器和标记   扩展为XAML。

To be instantiated as an object element in XAML, a custom class must meet the following requirements:
The custom class must be public and must expose a default (parameterless) public constructor. (See following section for notes regarding structures.)
The custom class must not be a nested class. The extra "dot" in the full-name path makes the class-namespace division ambiguous, and interferes with other XAML features such as attached properties.
If an object can be instantiated as an object element, the created object can fill the property element form of any properties that take the object as their underlying type.
You can still provide object values for types that do not meet these criteria, if you enable a value converter. For more information, see Type Converters and Markup Extensions for XAML.

在这里,你有两个选择:
1)使用类型转换器
使用类型转换器可以让你实例化对象没有参数的构造函数,但是你必须提供一个类型转换器,将做实例。

From there, you have two choices:
1) Using a TypeConverter:
Using a type converter will allow you to instantiate an object without a parameterless constructor, but you will have to provide a TypeConverter that will do the instantiation.

现在,我从来没有使用它,我不能帮你进一步说。

Now, I never had to use it, I cannot help you further with that.

2)获取IService使用服务定位:

2) Retrieve IService using the ServiceLocator:

public class MyUserControl : UserControl
{    
    public IService Service { get; set; }

    public MyUserControl()
    {
       Service = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<IService>();
       // You can do something with Service here already.
    }
}

我知道这是你的类的设计发生了变化,但希望你能应付它。

I realize it is a change in the design of your class, but hopefully you can cope with it.

希望这有助于

的巴布。

这篇关于使用MEF对照XAML的实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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