views:

43

answers:

1

Hi all,

I'm having some troubles trying to dynamically generate content in WPF and after it bind data.

I have the following scenario: TabControl - Dynamically generated TabItems through DataTemplate - inside TabItems, I have dynamic content generated by DataTemplate that I wish to bind (ListBox).

The code follows:

::TabControl

<TabControl Height="252" HorizontalAlignment="Left" Name="tabControl1" VerticalAlignment="Top" Width="458" Margin="12,12,12,12" ContentTemplate="{StaticResource tabItemContent}"></TabControl>

::The Template for TabControl to generate TabItems

<DataTemplate x:Key="tabItemContent">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <ListBox ItemTemplate="{StaticResource listBoxContent}" ItemsSource="{Binding}">
            </ListBox>
        </Grid>
    </DataTemplate>

::The template for ListBox Inside each TabItem

<DataTemplate x:Key="listBoxContent">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="22"/>
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Image Grid.Column="0" Source="{Binding Path=PluginIcon}" />
            <TextBlock Grid.Column="1" Text="{Binding Path=Text}" />
        </Grid>        
    </DataTemplate>

So, when I try to do this on code inside a loop to create the tabitems:

TabItem tabitem = tabControl1.Items[catIndex] as TabItem;
   tabitem.DataContext = plugins.ToList();

where 'plugins' is an Enumerable

The ListBox is not bounded. I tried also to find the ListBox inside the TabItem to set the ItemSource property but no success at all.

Someone have an idea on how to do that? Thanks in advance.

A: 

The template for TabControl uses a ContentPresenter to presents the SelectedContent, like this:

 <ContentPresenter Content="{TemplateBinding SelectedContent}"
                   ContentTemplate="{TemplateBinding ContentTemplate}" />

A ContentPresenter's job in life is to expand a DataTemplate. As it does so it sets the DataContext of the constructed visual tree to its Content property, which in this case is bound to SelectedContent.

The SelectedContent is set from the TabItem's Content property, not its DataContext. So setting the DataContext on the TabItem doesn't set the DataContext on the content area's visual tree.

What you want is:

tabItem.Content = plugins.ToList();
Ray Burns
Thanks so much Ray. It worked!
Bataglião