我正在尝试从另一个视图模型打开一个新页面。 我正在这样做:
我的页面已注册:
builder.Services.AddSingleton<SettingsPageView, SettingsPageViewModel>();
builder.Services.AddSingleton<WifiPageView, WifiPageViewModel>();
在我的SettingsPageView 中我这样做:
<Button TextColor="Black" Command="{Binding ClickedWifiMenuCommand}" Text="WIFI Menu"/>
命令如下:
[RelayCommand]
public async void ClickedWifiMenu()
{
Navigation.PushAsync(new WifiPageView());
}
但这不起作用。
我的 Wifipage:
public partial class WifiPageViewModel: ObservableObject
{
private readonly ILocalizationResourceManager _loc;
private readonly ILogger _logger;
public WifiPageViewModel(ILocalizationResourceManager loc, ILogger logger)
{
_loc = loc;
_logger = logger.ForContext<WifiPageViewModel>();
}
背后代码:
public WifiPageView(WifiPageViewModel vm)
{
InitializeComponent();
BindingContext = vm;
}
还有我的空洞观点:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
...
x:DataType="ViewModels:WifiPageViewModel">
<StackLayout>
<Label Text="Hi mom"/>
</StackLayout>
</ContentPage>
如何从单一视图打开我的视图?
首先,请确保您的
MainPage
类型为Shell
或NavigationPage
:
导航页面:
public App(SettingsPageView settingpage)
{
InitializeComponent();
MainPage = new NavigationPage(settingpage);
}
AppShell (也可以使用
builder.Services.AddSingleton<AppShell>()
来注册
):
public App(AppShell appshell)
{
InitializeComponent();
MainPage = appshell;
}
// if you didn't register it you it can just be
public App()
{
InitializeComponent();
MainPage = new AppShell();
}
然后,因为你注册了WifiPageView,所以我建议你从
Services
而不是new
获取它的实例:
[RelayCommand]
public async void ClickedWifiMenu()
{
var wifipage = App.Current.MainPage.Handler.MauiContext.Services.GetService<WifiPageView>();
App.Current.MainPage.Navigation.PushAsync(wifipage);
}
如果你使用shell,可以查看官方提供的关于Shell Naviagtion H.A.H的文档。