Design-time DataContext in a DataTemplate?
Asked Answered
H

2

8

When I put a DataTemplate in a <Page.Resources> section, it inherits the DataContext of the Page when editing bindings inside the designer. However at run-time the DataTemplate is being used by an element inside the Page which has its own DataContext. I want the designer to show the inner DataContext while binding instead.

Is there a tag like d:DataContext for DataTemplates? Setting DataType doesn't do anything.

Hecatomb answered 19/6, 2013 at 9:47 Comment(0)
H
11

I found you can just set d:DataContext on the root element inside the DataTemplate.

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

<ListBox ItemsSource="{Binding People}">
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel d:DataContext="{d:DesignInstance Type=local:Person}">
            <TextBlock Text="{Binding Name}" />
            <TextBlock Text="{Binding Age}" />
            <TextBlock Text="{Binding Height}" />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

Hecatomb answered 25/6, 2013 at 6:51 Comment(1)
The Type parameter is unnecessary because it's part of the default constructor if you omit it.Superpose
M
10

I realize this is super old but for the sake of making SO better. DataTemplates have a "DataContext" through the DataType tag.

<DataTemplate DataType="{x:Type local:Person}">
    <StackPanel>
        <TextBlock Text="{Binding Name}" />
        <TextBlock Text="{Binding Age}" />
        <TextBlock Text="{Binding Height}" />
    </StackPanel>
</DataTemplate>
Monocarpic answered 19/1, 2018 at 21:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.