tags:

views:

52

answers:

1

What is wrong with DataTemplate x:Key="CellTemplate" not reaching the DataContext of the Grid's ContentControl?

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="WpfApplication1.Page1">
    <Page.Resources>
        <XmlDataProvider x:Key="xml">
            <x:XData>
                <root xmlns="">
                    <foo a="one" />
                    <foo a="two" />
                    <foo a="three" />
                    <foo a="four" />
                </root>
            </x:XData>
        </XmlDataProvider>
    </Page.Resources>
    <Grid DataContext="{Binding Mode=Default, Source={StaticResource xml}}">
        <Grid.Resources>
            <DataTemplate x:Key="CellTemplate">
                <TextBlock Foreground="AntiqueWhite"
                           Text="{Binding Mode=Default, XPath=.}" />
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding XPath=.}" Value="three">
                        <Setter Property="TextBlock.FontWeight" Value="Bold" />
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ContentControl Grid.Row="0" 
            ContentTemplate="{StaticResource CellTemplate}"
            DataContext="{Binding Mode=Default, XPath=/root/foo[1]/@a}" />    
        <ContentControl Grid.Row="1"
            ContentTemplate="{StaticResource CellTemplate}"
            DataContext="{Binding Mode=Default, XPath=/root/foo[2]/@a}" />    
        <ContentControl Grid.Row="2" 
            ContentTemplate="{StaticResource CellTemplate}"
            DataContext="{Binding Mode=Default, XPath=/root/foo[3]/@a}" />
        <ContentControl Grid.Row="3" 
            ContentTemplate="{StaticResource CellTemplate}"
            DataContext="{Binding Mode=Default, XPath=/root/foo[4]/@a}" />
    </Grid>
</Page>
+1  A: 

Figured it out, it's confusing, but the data context inside the data template is set to the content of the content control, not to its data context. Instead of setting the data context of each content control, set its content.

Example:

<ContentControl Grid.Row="1"
    ContentTemplate="{StaticResource CellTemplate}"
    Content="{Binding Mode=Default, XPath=/root/foo[1]/@a}" />

Or, alternatively:

<ContentControl Grid.Row="0" 
    ContentTemplate="{StaticResource CellTemplate}"
    DataContext="{Binding Mode=Default, XPath=/root/foo[1]/@a}" 
    Content="{Binding}" />  
Aviad P.
This has no effect.
rasx
Try this.......
Aviad P.
You got it! ...and in the extreme case, instead of a `ContentControl`, I might consider a user control...
rasx