I have a form with a ListBox containint a number of items. Each of the items is supposed to have a title and an image. Here's my XAML:
<ListBox x:Name="MyList" HorizontalAlignment="Left" Height="384" Margin="10,505,0,0" VerticalAlignment="Top" Width="366"
ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!--This works:-->
<Label Content="{Binding Title}"/>
<!--This doesn't:-->
<Image Width="50" Height="50" Source="{Binding Cover}" Stretch="UniformToFill"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My data class looks somewhat like this:
class Data
{
public BitmapImage Cover{ get; set; }
public string Title{ get; set; }
}
I'm getting the BitmapImage
from a Bitmap
like this:
Data data;//this is my data object
Bitmap bitmap;//this is my bitmap. It holds a valid image, I've checked.
MemoryStream memory = new MemoryStream();
bitmap.Save(memory, ImageFormat.Bmp);
memory.Position = 0;
data.Cover = new BitmapImage();
data.Cover.BeginInit();
data.Cover.StreamSource = memory;
data.Cover.CacheOption = BitmapCacheOption.OnLoad;
data.Cover.EndInit();
Finally, I set the list's data like this:
MyList.ItemsSource = dataList;//dataList is a List<Data>
Binding the title (or other simple properties like dates or int
properties) to a Label works fine, however the image doesn't show up. How do I make it display properly?
So you Cover
property in your Data
class needs to raise a property changed event to let the view know it needs to get the image again as it has changed. To do this is simple:
class Data, INotifyPropertyChanged
{
private BitmapImage _cover;
public BitmapImage Cover
{
get { return _cover; }
set
{
_cover = value;
OnPropertyChanged("Cover");
}
}
public string Title{ get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Your Cover init code is working fine in my project. I think you forgot to post the following line: dataList.Add(data); I don't know why you set the ItemsSource property twice. If you use MVVM and you bind the ItemsSource property, you shouldn't set that property from code ( MyList.ItemsSource = dataList;) Instead, I would suggest ItemsSource="{Binding} dataList" in the XAML.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.