查看网格中的图像和文本 [英] Viewing images and text in a grid

查看:107
本文介绍了查看网格中的图像和文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图标和文本查看为表格,因此代码看起来像

MyItemType.cs

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



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



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?

推荐答案

据我了解,在XAML中绑定图像时,该图像必须为BitmapImage类型.因此,您可以将MyItemType类中的Image的类型更改为BitmapImage而不是byte [].您不必将其转换为字节.
简而言之,这就是您要做的.

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.

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



并删除转换,只需执行以下操作即可:



And remove the conversions and simple do this :

newItem.Image = b;



现在应该可以使用了.

顺便说一下,您不必在WPF引擎可以理解的DataTemplate中显式地编写DataType.因此,您可以为DataTemplate指定键,然后将ItemTemplate分配给ListBox.

希望对您有所帮助!



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!


这篇关于查看网格中的图像和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆