mvvmcross navigate to viewmodel from tabbed
我有一个使用mvvmcross的Xamarin Forms应用程序。在那里,我可以通过TabbedPages进行导航。每个页面后面都有一个xaml代码和viewmodel。
第一页的相关代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <?xml version="1.0" encoding="utf-8" ?> <pages:BaseTabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:pages="clr-namespace:ABBI_XPlat_3.Pages;assembly=ABBI_XPlat_3" x:Class="ABBI_XPlat_3.Pages.DeviceListPage" Title="Discover devices" x:Name="DevicePage"> <pages:BaseTabbedPage.Resources> <ResourceDictionary> <DataTemplate x:Key="DeviceItemTemplate"> ... </DataTemplate> </ResourceDictionary> </pages:BaseTabbedPage.Resources> <pages:BaseTabbedPage.Children> <pages:BasePage Title="Scan for devices"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> </Grid.RowDefinitions> <StackLayout BackgroundColor="#FF6969" Padding="10" IsVisible="{Binding IsStateOn, Converter={StaticResource InverseBoolean}}"> <Label Text="{Binding StateText}" FontSize="18" HorizontalTextAlignment="Center"></Label> </StackLayout> <ListView Grid.Row="1" ItemsSource="{Binding Devices}" SelectedItem="{Binding SelectedDevice, Mode=TwoWay}" IsPullToRefreshEnabled="True" RefreshCommand="{Binding RefreshCommand}" IsRefreshing="{Binding IsRefreshing, Mode=OneWay}" RowHeight="80" ItemTemplate="{StaticResource DeviceItemTemplate}"> </ListView> <StackLayout Grid.Row="2" Orientation="Horizontal"> <Button Text="Connect" Command="{Binding ConnectToSelectedCommand}" HorizontalOptions="FillAndExpand"/> <Button Text="Stop Scan" Command="{Binding StopScanCommand}" HorizontalOptions="End"/> <ActivityIndicator IsRunning="{Binding IsRefreshing}" HeightRequest="24" WidthRequest="24" VerticalOptions="Center" HorizontalOptions="End"/> </StackLayout> </Grid> </pages:BasePage> <pages:ServiceListPage Title="Services"/> <pages:OtherTabbedPage Title="Services"/> </pages:BaseTabbedPage.Children> </pages:BaseTabbedPage> |
我可以使用以下方法从主视图模型中的按钮调用不同的视图模型:
1 2 3 4 5 6 | public MvxCommand ConnectToSelectedCommand => new MvxCommand(ConnectToSelectedDeviceAsync, CanDisplayServices); private async void ConnectToSelectedDeviceAsync() { ShowViewModel<ServiceListViewModel>(new MvxBundle(new Dictionary<string, string> { { DeviceIdKey, SystemDevices.FirstOrDefault().Id.ToString() } })); } |
在我的主要ViewModel中。但是我希望能够使用选项卡在ViewModel之间导航。此刻,如果我单击选项卡,则会显示该页面,但没有关联的ViewModel。
请帮助!
因此要使MvvmCross将页面绑定到VM,要做的就是将MvxTabbedPage作为Root TabbedPosition
终于设法解决了这个问题。太简单了,我找不到任何答案。我只需要在页面的代码后面添加一个绑定上下文。
1 2 3 4 5 | public ServiceListPage() { InitializeComponent(); this.BindingContext = new ViewModels.ServiceListViewModel(Plugin.BLE.CrossBluetoothLE.Current.Adapter, UserDialogs.Instance); } |