zclmoon
zclmoon

Reputation: 149

How to bind and change pages in a tab control with a viewmodel?

I have three xaml pages and related ViewModels: main.xaml, MainViewModel.cs; page1.xaml, Page1ViewModel.cs; page2.xaml, page2ViewModel.cs. There is a TabControl in main.xaml. I want to load and show the page1.xaml in TabItem when the application initializing, and page1.xaml will be changed to page2.xaml when clicking the button included in page1.xaml; page2.xaml will be changed to page1.xaml when clicking the button included in page2.xaml.

All the events or commands need to be implemented in ViewModels. My Questions:

  1. How to load the pages to the TabItem?
  2. How to change the page in the TabItem?

Above questions have been solved by Rachel, Thanks.

  1. I want show page1 and page2 in TabItem1, page1 will disappear and page2 will show when clicking the button which included in page1.

Thanks.

Upvotes: 0

Views: 1960

Answers (1)

Rachel
Rachel

Reputation: 132678

Your MainPageViewModel should hold a collection of what pages are in the TabControl, and the SelectedPage. It should also contain an ICommand which will change the current page.

For example,

// These should be full properties that raise PropertyChange notifications
public ObservableCollection<IPageViewModel> Tabs { get; set; }
public int SelectedTabIndex { get; set; }
private ICommand ChangeTabIndexCommand { get; set; }

MainPageViewModel()
{
    Tabs = new ObservableCollection<IPageViewModel>();

    Tabs.Add(new Page1ViewModel());
    Tabs.Add(new Page2VieWModel());

    SelectedTab = 0;

    ChangeTabIndexCommand = new RelayCommand<int>(ChangeTab);
}

void ChangeTab(int newIndex)
{
    if (newIndex >= 0 && newIndex < Tabs.Count())
        SelectedTab = newIndex;
}

Your MainView would look like this:

<TabControl ItemsSource="{Binding Tabs}" SelectedIndex="{Binding SelectedIndex}" />

If you are using Silverlight 5, I believe you can use implicit DataTemplates, however if not you'll have to use something like a DataTemplateSelector or a Converter to tell Silverlight how to draw each ViewModel. I usually use Microsoft PRISM's DataTemplateSelector

There are a number of ways to hook up the ChangeTabIndexCommand. My preference is to use some kind of Messaging System, however you could also hook up the event in the Constructor of the MainViewModel.

Upvotes: 1

Related Questions