Question

I would like to make TabControl that contains TabItems. Within the TabItem, I would have StackPanel that contains various controls (ListBox, TextBox, Grid, etc). How do I make template of each TabItem and make multiple of them?

For example lets say I would like to make TabControl that contains tabs for Food category (Meat, Fruit, Vege, etc). I could make them individually by making TabItems with Name and Header. But instead I would like to just make one like following and use it as template as tab could increase.

<TabControl x:Name="TabControl" Margin="3,3,3,3" MinWidth="200">
    <TabItem Name="FoodCategory1">
        <!-- Contents of this does not really matter but its same thing for each "FoodCategory" -->
        <StackPanel>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition MinWidth="20"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBox x:Name="InputBox" Grid.Column="0" Margin="5,5,5,5"></TextBox>
                <Button x:Name="AddButton" Grid.Column="1" HorizontalAlignment="Right" Margin="0,0,5,0" Width="20" Height="20"></Button>
                <Button x:Name="RemoveButton" Grid.Column="2" HorizontalAlignment="Right" Margin="0,0,5,0" Width="20" Height="20"></Button>
            </Grid>

            <ListBox x:Name="FoodList" Margin="3,3,3,3" MinHeight="40"></ListBox>
        </StackPanel>
        <!-- example end -->
    </TabItem>
</TabControl>

And of course from my code back I would like to access each individual tabitems content by FoodCategoryX.InputBox and so forth. How should I approach this?

Any help would be appreciated.

Thank you.

Was it helpful?

Solution

Based upon what you wrote, you would write either a UserControl or CustomControl that acts as a container and provides the visual effects you are after. The simplest of these two is probably a UserControl. You would then populate each of your TabItems with an instance of your control and that enables your need to address the TabItems by name.

For your other question about addressing the various child controls by name, this is achievable, but a more robust approach would be to employ WPF's binding features by exposing dependency properties. Writing a UserControl is straight-forward effort and there's a working sample here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top