2

I have Xaml WPF window with TabControl inside. Each TabItem of it contains a page inside frame like this:

 <TabItem >
            <TabItem.Header>
                Users
            </TabItem.Header>
            <Frame Source="/Views/UsersPage.xaml"  />
 </TabItem>
 <TabItem>
            <TabItem.Header>
                Stats
            </TabItem.Header>
            <Frame Source="/Views/OrdersPage.xaml"/>
</TabItem>

The problem is when i open this window all pages inside frames loads simultaneously, so if , eg, I put MessageBox on each page load i got a lot of them. I want my pages to load only when I click on corresponding tab header. How can i achieve this?

Andrey Ischencko
  • 800
  • 1
  • 6
  • 18
  • 1
    Put your `Frame.Source` or `MessageBox` assignment into a custom init function and call it upon `SelctionChanged` of the `TabControl` in the corresponding `TabItem` that got selected. – Frank J May 08 '15 at 18:26
  • 1
    Possible duplicate of http://stackoverflow.com/questions/4756657/lazy-loading-in-tabcontrols-mvvm . You are looking for lazy loading, which would load the current tab on demand vs all at once –  May 08 '15 at 18:27

1 Answers1

1

One possible solution would be to inherit from TabItem like this:

public class MyCustomTabItem : TabItem
{
    public void MyCustomInitFunction()
    {
        //Do all your stuff here
    }
}

In there put all your stuff that is supposed to be happening when the control gets clicked.

Create your TabControl with those new items:

<TabControl SelectionChanged="myTabControl_SelectionChanged" Name="myTabControl">
    <MyCustomTabItem Name="myTab1">
        <MyCustomTabItem.Header>
            Users
        </MyCustomTabItem.Header>
        <Frame Source="/Views/UsersPage.xaml"  />
     </MyCustomTabItem>
     <MyCustomTabItem Name="myTab2">
        <MyCustomTabItem.Header>
            Stats
        </MyCustomTabItem.Header>
        <Frame Source="/Views/OrdersPage.xaml"/>
    </MyCustomTabItem>
</TabControl>

Hookup the SelectionChanged event handler to call your special init function:

private void myTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    TabControl tc = (TabControl)e.Source;
    if(tc != null)
    {
        MyCustomTabItem ti = (MyCustomTabItem)tc.Items[tc.SelectedIndex];
        if(ti != null)
        {
            ti.MyCustomInitFunction()
        }
    }
}

If you only want this to happen the first time it get's shown put a bool variable in your MyCustomTabItem class that keeps track if it has already happened once, and if so just return instead of running it again.

Frank J
  • 1,666
  • 13
  • 19