65.9K
CodeProject 正在变化。 阅读更多。
Home

如何在 Phone7.Fx 中使用 IOC 容器和 MVVM

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.09/5 (3投票s)

2011年11月7日

CPOL

2分钟阅读

viewsIcon

22921

downloadIcon

315

如何在 Phone7.Fx 中使用 IOC 容器和 MVVM

引言

在这篇文章中,我将解释如何在简单的 Windows Phone 应用中使用 Phone7.Fx 的 IOC 容器和 MVVM 模式。

背景

如果您需要更多关于 IOC 和 MVVM 的细节,请查看维基百科中的定义:MVVM - IOC

使用代码 

示例(您可以在下方找到下载链接)包含一个视图、一个视图模型和一个服务。

img1.png

View

视图是一个简单的 XAML 页面,位于 Views 目录中(这不是强制性的,但在 Visual Studio 中更清晰)。第一步是在 XAML 代码中添加一个名为 ViewModelBehavior 的行为。

<i:Interaction.Behaviors><Mvvm:ViewModelBehavior/></i:Interaction.Behaviors> 

该行为用于自动查找关联的 ViewModel 并将其绑定到 Viewdatacontext
下一步是在代码背后添加一个 IMainView,它实现了 IViewMainView 类实现了 IMainView 接口。

public interface IMainView:IView{    }
public partial class MainView : IMainView
{
   // Constructor
   public MainView()
   {
     InitializeComponent();
   }
}

注册一个服务。 在我们的例子中,HelloService 提供了一些数据。 该服务实现了 IHelloService

public class HelloService:IHelloService
{
   public string SayHello()
   {
     return "Hello Phone7.Fx !"
   }
}

使用 IOC 容器,构建和管理 HelloService 实例的工作不是我们的责任。

App.xaml.cs 文件中的 Application_Launching 方法中,我们注册 IHelloServiceHelloService 之间的映射。 在这种情况下,当我们需要 IHelloService 的实现时,IOC 容器将解析映射并提供 HelloService 的一个实例。

private void Application_Launching(object sender, LaunchingEventArgs e)
{
    Container.Current.RegisterType<IHelloService, HelloService>();
}

ViewModel

视图模型通过 ViewModelBehavior 自动绑定到视图的 datacontext。 为了真正地链接它们,我们必须在视图模型类上添加一些属性。

ViewModel 属性将 ViewModel 链接到 View。 在我们的例子中,viewmodel 需要 IHelloService 的一个实现。 感谢 IOC 容器,MainViewModel 对象被自动实例化,并且提供了 IHelloService 的一个实例。

现在,可以调用 IHelloServiceSayHello 方法并设置 Message 属性的值。

viewmodel 上使用 IOC 非常有用,因为它现在很容易模拟和实现视图模型的单元测试。

[ViewModel(typeof(MainView))]
public class MainViewModel : ViewModelBase<IMainView>
{
    private readonly IHelloService _helloService;
    [Injection]
    public MainViewModel(IMainView view, IHelloService helloService) : base(view)
    {
      _helloService = helloService;
    }

    public override void InitalizeData()
    {
      Message = _helloService.SayHello();
      base.InitalizeData();
    }

    private string _message;
    public string Message
    {
      get { return _message; }
      set { _message = value; RaisePropertyChanged("Message"); }
    }
}

再次查看视图

视图模型绑定到视图的 datacontext,现在我们可以将视图模型属性绑定到 XAML 代码中的视图控件。

<TextBlock Text="{Binding Message}" />

结论

在这篇文章中,我们已经看到,在 WP7 项目中使用 IOC 容器和 MVVM 模式非常有用且简单。

历史

  • 2011 年 11 月 7 日:初始文章
© . All rights reserved.