开发者

Images in table

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"&开发者_JS百科gt;
    <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 window. Does anybody have an idea of what's wrong?


Image.Source needs to be of type ImageSource (MSDN link). It does not know how to handle an array of bytes, as far as I know.


agreed with Jens, Image.Source has to be of Type ImageSource (or BitmapImage)

You should do something like this:

string path = @"C:\Users\Eliazar\Pictures\1556.bmp";

BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri(path, UriKind.Absolute);
source.EndInit();

newItem.Image = new Image() { Source = source };
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜