当您在WPF或UWP中使用MVVM Light时,您可以使用触发器等导航到页面的触发器使用触发器事件Load。
像这样:
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:InvokeCommandAction Command="{Binding LoadedCommand}" />
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
这就是命名空间:
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
但是如何在Xamarin.Forms
中执行此操作?它是一样的吗?我找不到一个例子。
更新
我的xaml页面:
对EventToCommandBehavior的引用:
xmlns:behaviors="clr-namespace:XamarinTest.Behaviors"
<ContentPage.Behaviors>
<behaviors:EventToCommandBehavior EventName="OnAppearing"
Command="{Binding LoadedCommand}" />
</ContentPage.Behaviors>
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
这是我的ViewModel:
public RelayCommand LoadedCommand { get; }
public UserMainViewModel()
{
LoadedCommand = new RelayCommand(LoadData);
}
private async void LoadData()
{
//...
}
xaml Page和ViewModel之间的绑定在Page1.xaml.cs中是这样的:
public Page1()
{
InitializeComponent();
BindingContext = App.Locator.UserMainViewModel;
}
错误:
at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj, System.Object[] parameters) [0x00017] in <657aa8fea4454dc898a9e5f379c58734>:0
at System.Reflection.MonoCMethod.DoInvoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x0007a] in <657aa8fea4454dc898a9e5f379c58734>:0
at System.Reflection.MonoCMethod.Invoke (System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <657aa8fea4454dc898a9e5f379c58734>:0
at System.Reflection.ConstructorInfo.Invoke (System.Object[] parameters) [0x00000] in <657aa8fea4454dc898a9e5f379c58734>:0
at MyProject.Services.NavigationService.NavigateTo (System.String pageKey, System.Object parameter) [0x000e8] in C:\Projects\MyProject\MyProject\MyProject\Services\NavigationService.cs:89
at MyProject.Services.NavigationService.NavigateTo (System.String pageKey) [0x00001] in C:\Projects\MyProject\MyProject\MyProject\Services\NavigationService.cs:42
at MyProject.ViewModels.LoginViewModel.Login () [0x00002] in C:\Projects\MyProject\MyProject\MyProject\ViewModels\LoginViewModel.cs:25
答案 0 :(得分:3)
您必须使用此处所述的EventToCommandBehavior https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/behaviors/reusable/event-to-command-behavior/
在您的页面中实现以下xaml: OnAppearing仅存在于页面上。 (没有加载事件)
<ContentPage.Behaviors>
<local:EventToCommandBehavior EventName="Appearing" Command="{Binding LoadedCommand}" />
<ContentPage.Behaviors>