**<controls:PanoramaItem Header="first item">
<!--Double line list with text wrapping-->
<ListBox Margin="0,0,-12,0" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Height="150">
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="Name" Text="Name: " TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Margin="5,0,0,0"/>
</StackPanel>
<TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding LineThree}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding LineFour}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>**
这是.xmal Part。但是我必须在c#中这样做。然后请帮我解决这个问题。
答案 0 :(得分:4)
ListBox listBox = new ListBox();
listBox.Margin = new Thickness(0, 0, -12, 0);
listBox.SetBinding(ListBox.ItemsSourceProperty, new Binding("Items"))
CreateItemTemplate(listBox);
PanoramaItem pi = new PanoramaItem();
pi.Header = "first item";
pi.Content = listBox;
在实施CreateItemTemplate
时,您有两个选择,要么以编程方式创建DataTemplate
,要么在ResourceDictionary
中创建资源并使用该资源。后者是迄今为止最简单,最好的方式。
以编程方式查看How to define a DataTemplate in code?
要使用资源,您可以这样
public void CreateItemTemplate(ListBox listBox)
{
object myDataTemplate = FindResource("myDataTemplateResource"); // This only works if the resource is available in the scope of your control. E.g. is defined in MyControl.Resources
listBox.SetResourceReference(ListBox.ItemTemplateProperty, myDataTemplate);
}