Tuesday 23 July 2013

'VisualTree' is set more than once - Windows Phone Error

The property 'VisualTree' is set more than once.

If you keep getting this error in your windows phone app, it should be from your XAML. If you have a DataTemplate(<DataTemplate>) and if it has more than one child, it throws this exception.
For example:
<ListBox>
 <ListBox.ItemTemplate>
  <DataTemplate>
   <Image Source="{Binding Path=Image}" />
   <TextBlock Text="{Binding Path=Name}" />
  </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>

Here there are two direct child controls in the DataTemplate - an Image controld and a TextBlock control. The error can be corrected by placing the two controls inside a container control like a StackPanel. So the above code can be converted as below:
<ListBox>
 <ListBox.ItemTemplate>
  <DataTemplate>
    <StackPanel>
   <Image Source="{Binding Path=Image}" />
   <TextBlock Text="{Binding Path=Name}" />
    </StackPanel>
  </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>

Now it complies with the rules that a DataTemplate can contain only one direct child control.

No comments:

Post a Comment