Richard
Richard

Reputation: 389

WP7 ContentPresenter passing DataContext to DataTemplate

I have a data item:

<SampleData:Item Title="Evening News" Channel="ABC" x:Key="sampleData0" />

In my xaml page, I have a ContentPresenter that displays this item.

<ContentPresenter ContentTemplate="{StaticResource dt1}" />

Here is the data template, dt1:

    <DataTemplate x:Key="t2">
        <Grid Background="#FF5599DD" DataContext="{StaticResource sampleData0}"  >
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>              
            <TextBlock Text="{Binding Title}" />
            <TextBlock Text="{Binding Channel}" Grid.Row="1" />             
        </Grid>         
    </DataTemplate>

This all works fine. But I want to put the data template into my dictionary.xaml file, so I have to move the data context from the DataTemplate and into the ContentPresenter.

Now my ContentPresenter looks like this:

<ContentPresenter ContentTemplate="{StaticResource dt1}" DataContext="{StaticResource sampleData0}" />

And the data template looks like this:

    <DataTemplate x:Key="t2">
        <Grid Background="#FF5599DD">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>              
            <TextBlock Text="{Binding Title}" />
            <TextBlock Text="{Binding Channel}" Grid.Row="1" />             
        </Grid>         
    </DataTemplate>

But this doesn’t work!

I have experimented with RelativeSource but no luck.

Anyone got any ideas?

Upvotes: 1

Views: 971

Answers (1)

Pavlo Glazkov
Pavlo Glazkov

Reputation: 20746

Instead of setting the DataContext on the ContentPresenter set the Content property. Like this:

<ContentPresenter Content="{StaticResource sampleData0}"
                  ContentTemplate="{StaticResource dt1}"/>

Upvotes: 4

Related Questions