views:

445

answers:

1

Hello,

I am trying to use an ItemsControl to display a DataTemplate. I have this simple example:

<navigation:Page.Resources>
 <DataTemplate x:Key="PictureResultsTemplate">
  <!--<Grid/> -->
  <TextBlock Text="Nick Was Here"></TextBlock>
 </DataTemplate>
</navigation:Page.Resources>    


<Grid x:Name="LayoutRoot">
    <Grid Margin="0,0,8,8">
     <Grid.RowDefinitions>
      <RowDefinition Height="0.102*"/>
      <RowDefinition Height="0.898*"/>
     </Grid.RowDefinitions>
     <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto"/>
      <ColumnDefinition Width="*"/>
     </Grid.ColumnDefinitions>

 <ItemsControl x:Name="PictureResults" Margin="0,8,0,0" Grid.Row="2" ItemTemplate="{StaticResource PictureResultsTemplate}">
 </ItemsControl>  

    </Grid>     

</Grid>

How come the textblock text is not visible? Thanks!

+1  A: 

I think you are going to need to set the ItemsSource or Items on the items control, or you will have not items to apply your ItemTemplate to.

No, you don't have to bind to a data source. You could add items directly in xaml. See below:

<UserControl
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="QuickTests.MainPage"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        Width="640" Height="480">
    <UserControl.Resources>
        <DataTemplate x:Key="myStringTemplate">
         <StackPanel>
          <TextBlock Text="{Binding}"/>
          <TextBlock Text="Yep, this is an item"/>
         </StackPanel>
        </DataTemplate>
    </UserControl.Resources>
                  <ItemsControl ItemTemplate="{StaticResource myStringTemplate}">
                        <ItemsControl.Items>
                            <System:String>hello</System:String>
                            <System:String>world</System:String>
                        </ItemsControl.Items>
                    </ItemsControl>
    </UserControl>
Justice
Are you saying that I HAVE to bind it to a data source? How would you have a textblock for labeling then?
Nick
@Nick: your template can contain textblock that has some static text as a label. However for an instance of your template to be created the items control would need to be bound to a collection that contains at least one item.
AnthonyWJones