gpt4 book ai didi

c# - 在从 XAML 实例化的控件中使用 MEF

转载 作者:太空狗 更新时间:2023-10-29 21:55:19 25 4
gpt4 key购买 nike

我创建了一个 UserControl,它使用 [Import] 属性导入多个部分。

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

public MyUserControl()
{
}

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

此 UserControl 是从 XAML 实例化的,因此它的导入未得到满足并且 OnImportsSatisfied 未被调用。

<local:MyUserControl />

我的问题是在 XAML 中创建我的类时如何满足它的导入。

最佳答案

来自 MSDN:

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) 使用 TypeConverter :
使用类型转换器将允许您在没有无参数构造函数的情况下实例化一个对象,但您必须提供一个将执行实例化的 TypeConverter。

现在,我从来没有用过它,我无法在这方面进一步帮助你。

2) 使用 ServiceLocator 检索 IService:

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.
}
}

我知道这是你类(class)设计的改变,但希望你能应付。

希望对您有所帮助,

宝贝。

关于c# - 在从 XAML 实例化的控件中使用 MEF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8667983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com