[英]Using Loaded Trigger in Xamarin.Forms
在WPF或UWP中使用MVVM Light時,可以使用觸發事件“加載”,例如使用導航到頁面的觸發器。
像這樣:
<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
執行此Xamarin.Forms
? 一樣嗎 我找不到一個例子。
UPDATE
我的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
您必須按照此處所述使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.