Согласно вашему описанию, вы хотите использовать привязку для TabbedPage от ViewModel, я делаю один пример, на который вы можете взглянуть, шаг:
Во-первых, создайте пользовательский TabbedPage, который содержит один BindableProperty ChildrenListProperty.
public class BindableTabbedPage: TabbedPage
{
public BindableTabbedPage()
{
}
public static BindableProperty ChildrenListProperty =BindableProperty.Create<BindableTabbedPage, IList>(o => o.ChildrenList, new List<Page>(), propertyChanged: UpdateList);
public IList ChildrenList
{
get { return (IList)GetValue(ChildrenListProperty); }
set { SetValue(ChildrenListProperty, value); }
}
private static void UpdateList(BindableObject bindable, IList oldValue, IList newValue)
{
var tabbedPage = bindable as BindableTabbedPage;
if (tabbedPage != null)
{
tabbedPage.Children.Clear();
foreach (var page in newValue)
{
tabbedPage.Children.Add((Page)page);
}
}
}
}
Затем, используя эту BindableTabbedPage, вот так:
<tab:BindableTabbedPage
x:Class="TabbedPageWithNavigationPage.TabbedPage1"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:tab="clr-namespace:TabbedPageWithNavigationPage"
ChildrenList="{Binding tabs}"
SelectedItem="{Binding selectedtab}"
mc:Ignorable="d">
<!-- Pages can be added as references or inline -->
</tab:BindableTabbedPage>
public partial class TabbedPage1 : BindableTabbedPage
{
public TabbedPage1()
{
InitializeComponent();
this.BindingContext = new tabbedpageviewmodel();
}
}
Это TabbedPage ViewModel:
public class tabbedpageviewmodel : ViewModelBase
{
public ObservableCollection<Page> tabs { get; set; }
private Page _selectedtab;
public Page selectedtab
{
get { return _selectedtab; }
set
{
RaisePropertyChanged("selectedtab");
}
}
public tabbedpageviewmodel()
{
tabs = new ObservableCollection<Page>();
tabs.Add(new Page1() { BindingContext = new page1viewmodel() });
tabs.Add(new Page2() { BindingContext = new page2viewmodel() });
selectedtab = tabs[0];
}
}
ViewModel page1 и Page2 вот так:
public class page1viewmodel : ViewModelBase
{
private string _content;
public string content
{
get { return _content; }
set
{
_content = value;
RaisePropertyChanged("content");
}
}
public page1viewmodel()
{
content = "Page 1";
}
}
public class page2viewmodel : ViewModelBase
{
private string _str;
public string str
{
get { return _str; }
set
{
_str = value;
RaisePropertyChanged("content");
}
}
public page2viewmodel()
{
str = "Page 2";
}
}
ViewModelBase - это класс, который реализует INotifyPropertyChanged
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Скриншот: