2014-10-04 129 views
0

任何人都可以举一个实现的例子吗?是否使用ViewModel实现INotifyPropertyChanged(并引发事件,如在Silverlight中完成)或其他方式? ViewModel如何绑定到视图?如何在Windows Phone 8.1应用程序(xaml)中实现MVVM?

到目前为止,我发现的所有示例都不完整或过时(请参阅Silverlight应用程序,而不是 Xaml应用程序)。

+0

如果您有兴趣,我在我的博客上有一个[简单的MVVM示例](http://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/)。正如Abdurrahman所说,MVVM是一种模式,所以无论您使用的是WPF还是Silverlight,模式都是相同的。 – Rachel 2014-10-04 18:28:54

+0

值得研究一些MVVM框架,Caliburn Micro现在支持WP8.1和Universal应用程序。 – 2014-10-05 09:10:01

+0

@HenkHolterman感谢您的建议,将检查出 – Arnthor 2014-10-05 09:20:58

回答

3

我目前在自己的Universal/W8.1/WP8.1应用程序中使用以下方法。该方法使用RArcher WinRT Toolkit,这是一个基于MVVM模式的实验工具包。 它提供了一种维护应用程序状态的方法,您可以使用ViewModelBase来实现INPC。 它也使用Unity dependency injection container

我想让ViewModelLocator成为一个应用程序范围的资源,所以我的Views可以很容易地访问它。

<Application.Resources> 
    <vm:ViewModelLocator x:Key="ViewModelLocator" /> 
</Application.Resources> 

视图可以使用它像这样:

<Page.DataContext> 
    <Binding Source="{StaticResource ViewModelLocator}" Path="MainViewModel" /> 
</Page.DataContext> 

ViewModelLocator看起来是这样的:

public sealed class ViewModelLocator 
{ 
    public ViewModelLocator() 
    { 
     RegisterIoCBindings(); 
    } 

    public IMainViewModel MainViewModel 
    { 
     get { return IocContainer.Get<IMainViewModel>(); } 
    } 

    private void RegisterIoCBindings() 
    { 
     IocContainer.Container.RegisterType(typeof(IMainViewModel), typeof(MainViewModel), 
     null, new ContainerControlledLifetimeManager()); 
    } 
} 

MainViewModelViewModelBase作为基类,并实现了IMainViewModel

public sealed class MainViewModel : ViewModelBase, IMainViewModel 
{ 
    private string myText; 
    [AutoState] 
    public string MyText 
    { 
     get { return myText; } 
     set 
     { 
      myText = value; 
      OnPropertyChanged(); 
     } 
    } 

    public MainViewModel() // You can use constructor injection here 
    {    
    } 
} 

这是基本设置。正如其他人所说的,MVVM是一种模式,并有许多方式来使用它。我会说,使用什么感觉很好;-)

如果你想知道更多关于这种方法,检查出工具包和统一DI。

+0

感谢您的详细解答,我会去检查一些框架,就像您所描述的那样。如果没有办法让MVVM开箱即可,我真的很失望。 – Arnthor 2014-10-05 10:51:11

+0

当然你可以自己连线,如果这是你的意思是“开箱即用”。只需在你的视图模型上实现INPC,就快完成了。 – Kaj 2014-10-05 11:26:40

+0

我会小心使用该ServiceLocator模式。如上所述,框架包含了统一性,因此您不妨将视图模型注入视图,而不是让视图采用这种依赖性命中。 – MrDosu 2015-02-12 11:46:55

2

没有区别,它是一样的。因为MVVM是一种模式。你可以很容易地实现它到你的Windows Phone应用程序。我为我的wp应用程序和EventToCommand行为使用MVVM Light来引发事件。我有一个应用程序开源于GitHub,你可以检查出来,如果你想。

+0

谢谢,会考虑一下。我喜欢它的标题中的'光'这个词。 – Arnthor 2014-10-05 10:52:25

4

在Windows RT的情况下,我会建议朝PRISM看。它提供了非常好的现代开发实践。您将获得合适的导航服务,应用程序生命周期管理,出色的MVVM支持以及非常灵活的视图和ViewModels解析机制。 您可以通过NuGet轻松将其添加到您的项目中。 它有很好的文档,所以如果你有任何问题,你可以在MSDN找到答案,甚至下载免费的书Prism for the Windows Runtime。我们的团队在使用PRISM构建项目方面拥有成功的经验。

+0

谢谢,会检查出来。 – Arnthor 2014-10-17 12:38:19

相关问题