<ListBox x:Name="listBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10" >
<TextBlock Text="{Binding title}"/>
<TextBlock Text="{Binding Description}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
What is the correct way to add this with source code?
edited:
tried this:
public static DataTemplate createDataTemplate()
{
return (DataTemplate)System.Windows.Markup.XamlReader.Load(
@"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007"">
<TextBlock Text=""{Binding Title}"" />
<TextBlock Text=""{Binding Description}"" />
<Image Source=""{Binding Image}"" />
</DataTemplate>"
);
}
when i call this:
for (int i=0; i<10; i++) {
ListBox lb = new ListBox();
lb.ItemTemplate = createDataTemplate();
//...then add to a pivotitem
}
i get this:
The property ‘System.Windows.FrameworkTemplate.Template’ is set more than once. [Line: 3 Position: 32]
why?
You could simply define the shared template in your App.xaml file under the “Resources” element.
Define it in App.xaml:
Access it in code:
Use it in your UI: