Messager:
A Word of Caution About Messenger
Messenger is a powerful component that can greatly facilitate the task of communication, but it also makes the code more difficult to debug because it is not always clear at first sight which objects are receiving a message. Use with care!
DispatcherHelper
因为 ViewModel 是一个 POCO,它不能访问 Dispatcher 属性,因此我需要通过另一种方式来访问主线程,以将操作加入队列中。这是 MVVM Light DispatcherHelper 组件的作用。
CheckBeginInvokeOnUI:
顾名思义,此方法首先执行检查。如果此方法的调用方已经在主线程上运行,则无需进行调度。在这种情况下会直接在主线程上立即执行委托。但如果此调用方是在后台线程上,则执行调度。
RaisePropertyChanged with CallerMemberName (.net 4.5 only):
protected void RaisePropertyChanged([CallerMemberName]string propertyName = "") { base.RaisePropertyChanged(propertyName); }
ServiceLocator and SimpelIoc:
App.xaml.cs:
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
Mainwindow.xaml:
...
DataContext="{Binding Main, Source={StaticResource Locator}}">
ViewModelLocator.cs:
static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register<IDataService, Design.DesignDataService>(); } else { SimpleIoc.Default.Register<IDataService, DataService>(); } SimpleIoc.Default.Register<MainViewModel>(); } public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } }
Use the SET-Methode:
public class ViewModelBaseEx : ViewModelBase { protected void Set<T>(ref T field, T newValue, [CallerMemberName] string propertyName = "") { Set(propertyName, ref field, newValue); } } public T Property { get { return _property; } set { Set(ref _property, value); } }
EventToCommand:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"
...
<StackPanel Background="Transparent"> <i:Interaction.Triggers> <i:EventTrigger EventName="Tap"> <command:EventToCommand Command="{Binding Main.NavigateToArticleCommand, Mode=OneWay, Source={StaticResource Locator}}" CommandParameter="{Binding Mode=OneWay}" /> </i:EventTrigger> </i:Interaction.Triggers>