大型WPF项目的参考结构
大型WPF项目的参考结构
介绍
选择恰当的结构对于软件项目的成功是非常重要的。如果你的体系结构具有不好的性能,当应用程序加载时用户会有不好的体验。此外,它的健壮性,可维护性或者可测试行也是非常重要的。
WPF提供了强有力的数据绑定框架。如果我们通过使用MVVM设计模式来利用这一点,通过使用依赖注入解耦视图,我们可以构建强有力的大型结构。
我们想要使用的关键组件或者设计模式:
- WPF数据绑定
- MVVM
- 依赖注入
- 来自System.Windows.Interactivity库中的行为
工作原理
基本思想是构建一个构建视图的依赖容器。视图拥有的ViewModel是被注入,其被绑定到DataContext。ViewModel为视图集中和提供从服务获取的数据或者命令,服务从构造函数中注入。服务在容器中是单例存在。
使用该体系结构允许你构建一个低耦合的视图,视图内部通过后台从服务获取的公共数据神奇的交织在一起。重新排列或者替换视图是非常简单的,因为它们彼此独立。
该体系结构的优势:
- UI元素更加轻松的替换,因为灵活的数据绑定
- 视图更加松耦合和快速组合在一起
- ViewModel可以使用传统的单元测试
- 每个服务都有一个单一的目的。能够非常轻松的开发大型的体系结构
初始化容器并且构建MainWindow
public class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<ICustomerService, CustomerService>();
container.RegisterType<IShoppingCarService, ShoppingCarService>();
MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}
注入ViewModel到View中
通过在属性上添加Dependency特性,以来容器解析并注入指定类型,然后创建视图。注入的ViewModel被直接地设置为视图的DataContext。视图本身不包含任何逻辑。
public class MainWindow : Window
{
public MainWindowViewModel ViewModel
{
set { DataContext = value; }
}
public MainWindow()
{
InitializeComponent();
}
}
实现ViewModel
public class MainWindowViewModel
{
priavate ICustomerService _customerService;
public MainWindowViewModel(ICustomerService customerService)
{
_customerService = customerService;
customers = new ListCollectionView(customerService.Customers);
}
public ICollectionView Customers{ get; private set;}
}
绑定数据到视图
<Window x:Class="WPF"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListBox ItemSource={Binding Customers}>
</Window>

浙公网安备 33010602011771号