开发者

Binding albumArt in AlbumCollection to listbox

开发者 https://www.devze.com 2023-04-04 22:49 出处:网络
How can I bind AlbumArt to my listbox? My code: <ListBox Name=\"albumLb\" Margin=\"0,0,-12,0\" ItemsSource=\"{Binding Items}\" SelectionChanged=\"albumLb_SelectionChanged\">

How can I bind AlbumArt to my listbox?

My code:

    <ListBox Name="albumLb" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="albumLb_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" Margin="0,0,0,17" >
                    <!--Replace rectangle with image-->
           开发者_JAVA百科         <Image Source="{Binding }"/>
                    <StackPanel Width="311">
                        <TextBlock Text="{Binding Name}" FontSize="28" />
                        <TextBlock Text="{Binding Artist}" Margin="12,-6,12,0"  Foreground="#FFE5CDCD"/>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

And in my code I use:

albumLb.ItemsSource = library.Albums;

I know that I can get the AlbumArt by library.Albums[int index].getAlbumArt() but I don't know how to bind it into my listbox.


What type does getAlbumArt() return? If it is simply a path to a file (say in Isolated Storage) then you'll have to write a converter to do the binding. Also, instead of having a function called getAlbumArt(), create a property named AlbumArt instead with a public getter, which will allow binding to it. Then you can bind the image using

<Image Source="{Binding AlbumArt}" />

Next, create a converter (by implementing the IValueConverter interface) that will take the path to a file in Isolated Storage, and load it into a BitmapImage which is then returned to the Image in your ListBox by the converter.

This question has details on how to do this.


On the other hand, if you need to download the image from some website, use WebClient.OpenReadAsync.

WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(OnImageDownloadCompleted);
wc.OpenReadAsync(new Uri("www.mywebsite.com/albumart/album1.jpg", UriKind.Relative));

void OnImageDownloadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  if (e.Error == null) {
    StreamResourceInfo sri = new StreamResourceInfo(e.Result as Stream, null);
    BitmapImage imgsrc = new BitmapImage();
    imgsrc.SetSource(sri.Stream);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消