XAML error: "The property 'VisualTree' is set more than once"

John picture John · Apr 9, 2014 · Viewed 14.3k times · Source

I'm trying to put two Grids in a DataTemplate.

I'm getting the following error with my code shown below.

Error: "The property 'VisualTree' is set more than once"

<DataTemplate x:Key="PareoItemTemplate">
    <Grid x:Name="gridColorEjercicio" Height="100" Width="350" Background="#FFF0F0F0" Margin="-11,0,0,0">
        <StackPanel Margin="0" Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
            <StackPanel Margin="0,10,15,0" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
                <TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="{Binding letter}" FontSize="24" FontFamily="Resources/Fonts/Programa Tutorias Bold.ttf#Programa Tutorias" Foreground="Black" VerticalAlignment="Center"/>
                <TextBlock TextWrapping="Wrap" Text="{Binding option}" FontSize="24" FontFamily="Resources/Fonts/Programa Tutorias Bold.ttf#Programa Tutorias" Width="253" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </StackPanel>
            <Grid VerticalAlignment="Center" Margin="5,10,5,0" HorizontalAlignment="Center">
                <Image Source="{Binding imageURI}" />
            </Grid>
        </StackPanel>
    </Grid>
    <Grid x:Name="gridPareoColorEjercicio" Height="100" Width="350" Background="#FFF0F0F0" Margin="-11,0,0,0">
        <StackPanel Margin="0" Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
            <StackPanel Margin="0,10,15,0" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
                <TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="{Binding letter}" FontSize="24" FontFamily="Resources/Fonts/Programa Tutorias Bold.ttf#Programa Tutorias" Foreground="Black" VerticalAlignment="Center"/>
                <TextBlock TextWrapping="Wrap" Text="{Binding option}" FontSize="24" FontFamily="Resources/Fonts/Programa Tutorias Bold.ttf#Programa Tutorias" Width="253" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </StackPanel>
            <Grid VerticalAlignment="Center" Margin="5,10,5,0" HorizontalAlignment="Center">
                <Image Source="{Binding imageURI}" />
            </Grid>
        </StackPanel>
    </Grid>
</DataTemplate>

Answer

Daniel Br&#252;ckner picture Daniel Brückner · Apr 9, 2014

A data template can only have one visual tree but you are defining two grids. If you want the two grids to appear next to each other or one below the other, wrap them in a StackPanel and set the property Orientation accordingly.

<DataTemplate>
   <StackPanel Orientation="Vertical">
      <Grid>[...]</Grid>
      <Grid>[...]</Grid>
   </StackPanel>
</DataTemplate>