【发布时间】:2015-10-01 17:10:48
【问题描述】:
如何使用 MEF 将数据从主机绑定到插件?
所以事情是这样的:
- 我使用 MVVM,所以我有我的模型、视图模型和视图。
- 我想使用 MEF 来扩展我的应用程序。
- 我想将所有数据存储在
MainViewModel中,这样每个插件都可以使用实际数据。 - 插件是
UserControl,在MainViewModel中将显示为ContentControl。
到目前为止我所拥有的:
MainViewModel- 型号
- 从
MainViewModel到 View 的数据绑定。 - 从文件夹 X 导入插件
我需要什么:
- 插件需要将MainViewModel 中的数据绑定到插件UI。
- 更改插件 UI 中的属性必须更新 MainViewModel 中的数据并更新所有其他插件的 UI。
插件接口:
public interface IPlugin
{
}
public interface IPluginData
{
string Name { get; }
}
MainViewModel:(它的一部分)
private MyModel myfirstmodel;
private DirectoryCatalog catalog;
private CompositionContainer container;
[ImportMany]
IEnumerable<Lazy<IPlugin, IPluginData>> Plugins;
public MainWindowViewModel()
{
string pluginPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
pluginPath = Path.Combine(pluginPath, "plugins");
if (!Directory.Exists(pluginPath))
Directory.CreateDirectory(pluginPath);
catalog = new DirectoryCatalog(pluginPath, "*.dll");
container = new CompositionContainer(catalog);
try
{
this.container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
模型
public class MyModel
{
private string message;
private int number;
private DateTime date;
public string Message { get { return message; } set { message = value; } }
public int Number { get { return number; } set { number = value; } }
public DateTime Date { get { return date; } set { date = value; } }
}
插件
[Export(typeof(IPlugin))]
[ExportMetadata("Name", "MyFirstPlugin")]
public partial class MyFirstPlugin : UserControl, IPlugin
{
public MyFirstPlugin()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//Change the message in MainWindowViewModel and the date when it gets changed.
}
}
我尝试使用INotifyPropertyChanged,但没有走那么远..
有没有人有一个非常好的教程或者可以告诉我如何做到这一点?
我会很感激“如何”,而不仅仅是“只使用INotifyPropertyChanged”。
这可能吗?
【问题讨论】:
标签: c# wpf mvvm data-binding mef