Binding Artist from ArtistCollection to PanoramaItem.Listbox on Windows Phone 7
How can I bind all the artists from the Artists
collection to a ListBox
in a PanoramaItem
?
<controls:PanoramaItem Header="Artist" Name="Pan3">
<!--Double line list with image placeholder and text wrapping-->
<ListBox Name="artistLb" Margin="0,0,-12,0" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<!开发者_运维技巧--Replace rectangle with image-->
<Rectangle Height="100" Width="100" Fill="#FFE5001b" Margin="12,0,9,0"/>
<StackPanel Width="311">
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>
and xaml.cs code:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
MediaLibrary library = new MediaLibrary();
int CountArtist = library.Artists.Count;
//binding the library.Artist to the Panorama item
}
Thanks!
In my answer I will assume you started from a Windows Phone Panorama Project and already added the reference to Microsoft.Xna.Framework to gain access to the media library.
When binding Ui object like the ListBox to code behind the best solution is to stick with the ViewModel approach that is already provided in the project. In your project you should find a MainViewModel. To this viewmodel add the following property:
private MediaLibrary _library;
public MediaLibrary Library
{
get
{
if (_library == null)
{
_library = new MediaLibrary();
}
return _library;
}
}
This property exposes the MediaLibrary to your xaml. The library is instantiated when called for the first time.
From your xaml it is now possible to bind to this property, I am only showing the ListBox.
<ListBox Margin="0,0,-12,0" ItemsSource="{Binding Library.Artists}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Height="78">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Notice that I am binding the ListBox to the subproperty Artists of the Library property we just created in the viewmodel. I edited the ItemTemplate to show just one TextBlock that binds to the Artist name.
On your emulator you will just see 1 artist as an example, to test this solution with a real device you will have to use the WPConnect tool, which is explained here
I hope this gets you going for now, please let me know if any questions remain.
Have you tried?
artistLb.DataContext = library.Artists;
精彩评论