WPF中Caliburn.Micro框架
时间: 2023-12-19 16:31:18 浏览: 204
Caliburn.Micro是一个轻量级的MVVM框架,它可以帮助我们更好地实现WPF应用程序的开发。下面是一些关于Caliburn.Micro框架的介绍和示例:
1.使用Caliburn.Micro实现MEF插件化开发,根据dll插件目录动态加载程序集和主程序的Tab页。
```csharp
// 在App.xaml.cs中添加以下代码
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// 创建插件管理器
var pluginManager = new PluginManager();
// 加载插件
pluginManager.LoadPlugins();
// 创建主窗口
var mainWindowViewModel = new MainWindowViewModel(pluginManager);
// 显示主窗口
var mainWindow = new MainWindow();
mainWindow.DataContext = mainWindowViewModel;
mainWindow.Show();
}
```
2.CM框架搭建、事件发布与订阅、log打印、ioc容器、Conductor的用法,框架下的命名约定以及事件绑定、Emgucv进行模板匹配、右键菜单、单例模式等等。
```csharp
// ViewModelBase.cs
public abstract class ViewModelBase : Screen
{
protected readonly IEventAggregator _eventAggregator;
protected readonly ILog _logger;
public ViewModelBase(IEventAggregator eventAggregator, ILog logger)
{
_eventAggregator = eventAggregator;
_logger = logger;
}
// 发布事件
protected void Publish<TEvent>(TEvent @event)
{
_eventAggregator.PublishOnUIThread(@event);
}
// 订阅事件
protected void Subscribe<TEvent>(Action<TEvent> action)
{
_eventAggregator.Subscribe(action, ThreadOption.UIThread);
}
// 打印日志
protected void Log(string message)
{
_logger.Info(message);
}
}
// ShellViewModel.cs
public class ShellViewModel : Conductor<object>.Collection.OneActive
{
private readonly IWindowManager _windowManager;
private readonly IEventAggregator _eventAggregator;
private readonly ILog _logger;
private readonly IContainer _container;
public ShellViewModel(IWindowManager windowManager, IEventAggregator eventAggregator, ILog logger, IContainer container)
{
_windowManager = windowManager;
_eventAggregator = eventAggregator;
_logger = logger;
_container = container;
// 订阅事件
_eventAggregator.Subscribe(this);
}
// 打开新窗口
public void OpenWindow()
{
var viewModel = _container.Resolve<NewWindowViewModel>();
_windowManager.ShowDialog(viewModel);
}
// 关闭窗口
public void CloseWindow()
{
TryClose();
}
// 处理事件
public void Handle(MyEvent @event)
{
// 处理事件
}
}
// ShellView.xaml
<UserControl x:Class="MyApp.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Menu Grid.Row="0">
<MenuItem Header="File">
<MenuItem Header="Open" cal:Message.Attach="OpenWindow" />
<MenuItem Header="Close" cal:Message.Attach="CloseWindow" />
</MenuItem>
</Menu>
<ContentControl Grid.Row="1" cal:View.Model="{Binding ActiveItem}" />
</Grid>
</UserControl>
```
阅读全文