TabbedPage
是 Xamarin.Forms 中的一个控件,它允许用户在多个页面之间进行切换,每个页面对应一个标签。MvvmCross 是一个流行的 MVVM 框架,用于简化 Xamarin 应用的开发。结合使用 TabbedPage
和 MvvmCross 可以创建结构清晰、易于维护的应用程序。
MVVM (Model-View-ViewModel):
MvvmCross:
TabbedPage:
以下是一个简单的示例,展示如何在 Xamarin.Forms 中使用 MvvmCross 和 TabbedPage。
public class MainViewModel : MvxViewModel
{
public ObservableCollection<TabItemViewModel> Tabs { get; set = new ObservableCollection<TabItemViewModel>(); }
public MainViewModel()
{
Tabs.Add(new TabItemViewModel { Title = "Home", ViewModelType = typeof(HomeViewModel) });
Tabs.Add(new TabItemViewModel { Title = "Settings", ViewModelType = typeof(SettingsViewModel) });
}
}
public class TabItemViewModel
{
public string Title { get; set; }
public Type ViewModelType { get; set; }
}
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:YourApp.ViewModels;assembly=YourApp"
x:Class="YourApp.Views.MainPage">
<TabbedPage.BindingContext>
<viewModels:MainViewModel />
</TabbedPage.BindingContext>
<TabbedPage.ItemsSource>
<Binding Path="Tabs" />
</TabbedPage.ItemsSource>
<TabbedPage.ItemTemplate>
<DataTemplate>
<NavigationPage>
<x:Arguments>
<views:TabContentPage Title="{Binding Title}" ViewModelType="{Binding ViewModelType}" />
</x:Arguments>
</NavigationPage>
</DataTemplate>
</TabbedPage.ItemTemplate>
</TabbedPage>
<?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="YourApp.Views.TabContentPage">
<ContentPage.Content>
<!-- Content goes here -->
</ContentPage.Content>
</ContentPage>
问题: 标签页切换时数据不更新。
原因: 可能是由于数据绑定没有正确设置或 ViewModel 没有实现 INotifyPropertyChanged
接口。
解决方法:
INotifyPropertyChanged
接口,并在属性变化时触发 PropertyChanged
事件。public class HomeViewModel : MvxViewModel
{
private string _title;
public string Title
{
get => _title;
set
{
_title = value;
RaisePropertyChanged(() => Title);
}
}
}
通过以上步骤,可以确保 TabbedPage
中的数据在切换标签页时能够正确更新。
领取专属 10元无门槛券
手把手带您无忧上云