gpt4 book ai didi

c# - 在 Xamarin.Forms 中使用 MVVM 进行页面导航

转载 作者:太空狗 更新时间:2023-10-29 17:28:32 29 4
gpt4 key购买 nike

我正在开发 xamarin.form 跨平台应用程序,我想通过单击按钮从一个页面导航到另一个页面。因为我不能在 ViewModel 中执行 Navigation.PushAsync(new Page2()); 因为它只能在 Code-Behid 文件中执行。请提出任何方法来做到这一点?

这是我的观点:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Calculator.Views.SignIn"
xmlns:ViewModels="clr-namespace:Calculator.ViewModels;assembly=Calculator">

<ContentPage.BindingContext>
<ViewModels:LocalAccountViewModel/>
</ContentPage.BindingContext>

<ContentPage.Content>
<StackLayout>
<Button Command="{Binding ContinueBtnClicked}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>

这是我的 ViewModel:

public class LocalAccountViewModel : INotifyPropertyChanged
{
public LocalAccountViewModel()
{
this.ContinueBtnClicked = new Command(GotoPage2);
}

public void GotoPage2()
{
/////
}

public ICommand ContinueBtnClicked
{
protected set;
get;
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanges([CallerMemberName] string PropertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
}

最佳答案

一种方法是您可以通过 VM 构造函数传递导航。由于页面继承自 VisualElement,因此它们直接继承了 Navigation 属性。

文件背后的代码:

public class SignIn : ContentPage
{
public SignIn(){
InitializeComponent();
// Note the VM constructor takes now a INavigation parameter
BindingContext = new LocalAccountViewModel(Navigation);
}
}

然后在您的 VM 中,添加 INavigation 属性并更改构造函数以接受 INavigation。然后您可以使用此属性进行导航:

public class LocalAccountViewModel : INotifyPropertyChanged
{
public INavigation Navigation { get; set;}

public LocalAccountViewModel(INavigation navigation)
{
this.Navigation = navigation;
this.ContinueBtnClicked = new Command(async () => await GotoPage2());
}

public async Task GotoPage2()
{
/////
await Navigation.PushAsync(new Page2());
}
...
}

请注意您应该修复的代码问题:GoToPage2() 方法必须设置为async 并返回Task 类型。此外,该命令将执行异步操作调用。这是因为您必须异步进行页面导航!

希望对您有所帮助!

关于c# - 在 Xamarin.Forms 中使用 MVVM 进行页面导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43254396/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com