views:

15

answers:

1

I have a TabControl where each tab contains a DataGrid. When the user switches between tabs it seems that the DataGrid is created from scratch. I say this becuase of three things that I've noticed: the columns are automatticaly recreated, the current sorted column is lost, and selection is lost.

I would love to be able to retain the current sorted view when the user returns to a tab page. They may be comparing lists and it doesn't make sense to have them resort each time. The databehind the scenes is not changing once it is created. However, the the tabs are bound to an observable collection because they need to be added/removed depending on how the application is being used.

ViewModel:

public ObservableCollection<DataTable> Tables
{
    get
    {
        return _tables; // Tables are added/removed through secondary methods
    }
}

View:

<TabControl ItemsSource="{Binding Path=Tables"}>
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Text>
                    <MultBinding StringFormat="{}{0} ({1})}>
                        <Binding Path="TableName"/>
                        <Binding Path="Rows.Count"/>
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <DataGrid
                AutoGeneratingColumns="True"
                IsReadOnly="True"
                ItemsSource="{Binding DefaultView}"
                />
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

Is there anyway to keep the current sort order of the datagrid when tabs are changed?

+1  A: 

I think this has to do with the TabControl behavior more than the Datagrid. I may be wrong, but the TabControl only has one content area, and switches the contents when you change the selected tab, which means that the content will get recreated no matter what you do. Not sure there's a simple workaround for this... I'd love to hear answers from more knowledgeable people.

Alex Paven
The TabControl was the culprit. I have found several work arounds since this post. Here is a link to one that I feel had the best solution. http://www.pluralsight-training.net/community/blogs/eburke/archive/2009/04/30/keeping-the-wpf-tab-control-from-destroying-its-children.aspx
Jerod Houghtelling