连接View和ViewModel:ViewModelLocator
1.实现IPreferenceStorage、PreferenceStorage类
2.注册
public class ViewModelLocator {
/// <summary>
/// 搜索结果页ViewModel
/// </summary>
public ResultPageViewModel ResultPageViewModel =>
SimpleIoc.Default.GetInstance<ResultPageViewModel>();
/// <summary>
/// ViewModelLocator
/// </summary>
public ViewModelLocator() {
SimpleIoc.Default.Register<ResultPageViewModel>();
SimpleIoc.Default.Register<IPoetryStorage, PoetryStorage>();
SimpleIoc.Default.Register<IPreferenceStorage, PreferenceStorage>();
}
}
3.App.xaml注册vm命名空间
xmlns:vm="clr-namespace:MasterDetailTemplate.ViewModels;assembly=MasterDetailTemplate"
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="ViewModelLocator" />
<!--Global Styles-->
<Color x:Key="NavigationPrimary">#2196F3</Color>
<Style TargetType="NavigationPage">
<Setter Property="BarBackgroundColor"
Value="{StaticResource NavigationPrimary}" />
<Setter Property="BarTextColor"
Value="White" />
</Style>
</ResourceDictionary>
</Application.Resources>
4.ResultPage.xaml (View层) Binding到ViewModel
BindingContext="{Binding ResultPageViewModel, Source={StaticResource ViewModelLocator}}"
ContentPage没有Command但有Appearing事件
5.安装依赖包:Behaviors.Forms 将Appearing事件关联到PageAppearingCommand
6.ContentPage.Behaviors
xmlns:b="clr-namespace:Behaviors;assembly=Behaviors"
<ContentPage.Behaviors>
<b:EventHandlerBehavior EventName="Appearing">
<b:ActionCollection>
<b:InvokeCommandAction Command="{Binding PageAppearingCommand}" />
</b:ActionCollection>
</b:EventHandlerBehavior>
</ContentPage.Behaviors>
7.ResultPage引入命名空间 ListViewBehavior
xmlns:s="clr-namespace:Xamarin.Forms.Extended;assembly=Xamarin.Forms.Extended.InfiniteScrolling"
<ListView.Behaviors>
<s:InfiniteScrollBehavior />
</ListView.Behaviors>
Behaviors机制用来扩展控件功能