Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
3.33/5 (3 votes)
See more:
I'm trying to view icons and text as a table, so the code looks like

MyItemType.cs

public class MyItemType
{    
public byte[] Image { get; set; }    
public string Title { get; set; }
}


MainWindow.cs

public MainWindow()    
{        
InitializeComponent();        
MemoryStream mstream = new MemoryStream();        
Bitmap b = new Bitmap(@"C:\Users\Eliazar\Pictures\1556.bmp");        
b.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);        
byte[] ba = mstream.ToArray();        
BinaryWriter writer = new BinaryWriter(mstream);        
writer.Write(ba);        
MyItems = new List<MyItemType>();        
MyItemType newItem = new MyItemType();        
newItem.Image = ba;        
newItem.Title = "FooBar Icon";        
MyItems.Add(newItem);        
this.MainGrid.DataContext = this;        
}    
public List<MyItemType> MyItems { get; set; }


MainWindow.xaml

<Window.Resources>    
<DataTemplate DataType="{x:Type local:MyItemType}">        
<StackPanel>            
<Image Source="{Binding Path=Image}"/>            
<TextBlock Text="{Binding Path=Title}"/>        
</StackPanel>    
</DataTemplate>
</Window.Resources>
<Grid Name="MainGrid">    
<ListBox ItemsSource="{Binding Path=MyItems}" Background="White" Width="400" HorizontalAlignment="Right" Margin="0,211.206,35,188.794">        
<ListBox.ItemsPanel>            
<ItemsPanelTemplate>                
<WrapPanel IsItemsHost="True"/>            
</ItemsPanelTemplate>        
</ListBox.ItemsPanel>    
</ListBox></Grid>


But nothing appears in the windoow. Does anybody have an idea of what's wrong?
Posted
Updated 8-Mar-11 20:11pm
v3

1 solution

From my understanding, When you bind an Image in XAML, it must be of type BitmapImage. So you can change the type of Image in your MyItemType class to BitmapImage instead of byte[]. You don't have to convert it into byte.
In short, this is what you have to do.

C#
public class MyItemType
{
public BitmapImage Image { get; set; }
public string Title { get; set; }
}


And remove the conversions and simple do this :
C#
newItem.Image = b;


It should work now.

By the way, you don't have to explicitly write the DataType in the DataTemplate as it will understood by the WPF Engine. So you can specify the key for the DataTemplate and assign the ItemTemplate to your ListBox.

Hope it helped!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900