任何人都可以举一个实现的例子吗?是否使用ViewModel实现INotifyPropertyChanged
(并引发事件,如在Silverlight中完成)或其他方式? ViewModel如何绑定到视图?如何在Windows Phone 8.1应用程序(xaml)中实现MVVM?
到目前为止,我发现的所有示例都不完整或过时(请参阅Silverlight应用程序,而不是 Xaml应用程序)。
任何人都可以举一个实现的例子吗?是否使用ViewModel实现INotifyPropertyChanged
(并引发事件,如在Silverlight中完成)或其他方式? ViewModel如何绑定到视图?如何在Windows Phone 8.1应用程序(xaml)中实现MVVM?
到目前为止,我发现的所有示例都不完整或过时(请参阅Silverlight应用程序,而不是 Xaml应用程序)。
我目前在自己的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());
}
}
的MainViewModel
有ViewModelBase
作为基类,并实现了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。
在Windows RT的情况下,我会建议朝PRISM看。它提供了非常好的现代开发实践。您将获得合适的导航服务,应用程序生命周期管理,出色的MVVM支持以及非常灵活的视图和ViewModels解析机制。 您可以通过NuGet轻松将其添加到您的项目中。 它有很好的文档,所以如果你有任何问题,你可以在MSDN找到答案,甚至下载免费的书Prism for the Windows Runtime。我们的团队在使用PRISM构建项目方面拥有成功的经验。
谢谢,会检查出来。 – Arnthor 2014-10-17 12:38:19
如果您有兴趣,我在我的博客上有一个[简单的MVVM示例](http://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/)。正如Abdurrahman所说,MVVM是一种模式,所以无论您使用的是WPF还是Silverlight,模式都是相同的。 – Rachel 2014-10-04 18:28:54
值得研究一些MVVM框架,Caliburn Micro现在支持WP8.1和Universal应用程序。 – 2014-10-05 09:10:01
@HenkHolterman感谢您的建议,将检查出 – Arnthor 2014-10-05 09:20:58