我有一个动态构建的网格控件。
我正在尝试添加一些其他控件,我的TextBlock显示正常,但Image没有。
是的,图像源是有效的BitmapImage。公司详细信息填充正确。
以下是代码:
Private Sub CreateItemContent(ByVal _Item As CompanyTyping.List, ByVal _TV As RadTileView)
Dim _Det = Company.CompanyDetails(_Item.CompanyID)
Dim item As New RadTileViewItem()
'create and define the inner grid
Dim _PG As New Grid()
Dim gridCol1 As New ColumnDefinition()
gridCol1.Width = New GridLength(200)
Dim gridCol2 As New ColumnDefinition()
gridCol2.Width = New GridLength(0, GridUnitType.Star)
_PG.ColumnDefinitions.Add(gridCol1)
_PG.ColumnDefinitions.Add(gridCol2)
'add the initial items to the initial grid
Dim _Img As New Image()
_Img.VerticalAlignment = Windows.VerticalAlignment.Top
_Img.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
_Img.Visibility = Windows.Visibility.Visible
_Img.MinHeight = 50
_Img.MinWidth = 200
_Img.Source = ByteArrayToImage(_Det(0).Logo)
Grid.SetColumn(_Img, 1)
_PG.Children.Add(_Img)
Dim _PGI As New Grid()
Dim gridRow1 As New RowDefinition()
gridRow1.Height = New GridLength(29)
Dim gridRow2 As New RowDefinition()
gridRow2.Height = New GridLength(29)
Dim gridRow3 As New RowDefinition()
gridRow3.Height = New GridLength(29)
Dim gridRow4 As New RowDefinition()
gridRow4.Height = New GridLength(0, GridUnitType.Star)
_PGI.RowDefinitions.Add(gridRow1)
_PGI.RowDefinitions.Add(gridRow2)
_PGI.RowDefinitions.Add(gridRow3)
_PGI.RowDefinitions.Add(gridRow4)
Grid.SetColumn(_PGI, 0)
_PG.Children.Add(_PGI)
Dim _TB1 As New TextBlock()
_TB1.Text = _Item.MainContact
Grid.SetRow(_TB1, 0)
_PGI.Children.Add(_TB1)
item.Header = _Item.Name & " - ID: " & _Item.CompanyID
_TV.Items.Add(item)
item.SetValue(RadTileViewItem.ContentProperty, _PG)
End Sub
和ByteArrayToImage:
Public Function ByteArrayToImage(_Bytes As Byte()) As System.Windows.Media.Imaging.BitmapImage
If _Bytes Is Nothing Then
Return Nothing
Else
Dim _bm As New BitmapImage()
Using _strm As New MemoryStream(_Bytes)
With _bm
.BeginInit()
.CacheOption = BitmapCacheOption.OnLoad
.StreamSource = _strm
.EndInit()
End With
End Using
Return _bm
End If
End Function
我已经验证过,在完整的XAML版本中,Image控件的来源正确显示图像...只是不在这里
答案 0 :(得分:1)
似乎设置
gridCol2.Width = New GridLength(0, GridUnitType.Auto)
会使图像按预期显示。
仅显示一些代码如何从包含编码图像缓冲区的字节数组创建BitmapImage,例如JPEG或PNG。对不起,这是C#,但我不会说VB。然而,它应该很容易翻译成VB。
byte[] buffer = ...
var bitmapImage = new BitmapImage();
using (var stream = new MemoryStream(buffer)) // create stream from buffer
{
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad; // necessary as stream is closed after EndInit
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
}
// stream is closed by leaving the using block
根本没有VB知识,我将其翻译如下:
Dim stream As New MemoryStream(buffer)
Dim bitmapImage As New BitmapImage()
bitmapImage.BeginInit()
bitmapImage.CacheOption = BitmapCacheOption.OnLoad
bitmapImage.StreamSource = stream
bitmapImage.EndInit()
stream.Close()