我有一个ComboBox,它应该显示两个值,一个字符串和一个图片。我有一些我添加到ComboBox的对象列表。这些对象具有字符串和位图字段。我可以在我的ComboBox中显示字符串,但我找不到显示位图的方法。
有没有办法让<Image/>
显示我的位图?
这是我的ComboBox XAML代码,我知道它不起作用,但我无法想到另一种方法。
<ComboBox x:Name="typeBox" Grid.Column="1" HorizontalAlignment="Left" Margin="10,318,0,0" VerticalAlignment="Top" Width="300" Height="29">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding name}" Grid.Column="0" Grid.Row="0"/>
<Image Width="20" Height="20" HorizontalAlignment="Right" Grid.Row="0" Grid.Column="1" Source="{Binding img}"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我的表单窗口的C#代码是相关的:
public NewRes()
{
pc = new PicChanger();
InitializeComponent();
typeBox.DataContext = GlowingEarth.types;
tagBox.DataContext = GlowingEarth.tags;
if (GlowingEarth.types.Count > 0)
{
foreach (Model.Type t in GlowingEarth.types)
{
typeBox.Items.Add(t);
}
}
if (GlowingEarth.tags.Count > 0)
{
foreach (Model.Etiquette t in GlowingEarth.tags)
{
tagBox.Items.Add(t);
}
}
}
我的资源(类型和礼仪)类的C#代码:
public class Type
{
private string mark;
public string name { get; set; }
private string desc;
private Bitmap img;
public Type(string m, string n, string d, Bitmap mg)
{
mark = m;
name = n;
desc = d;
img = mg;
}
}
public class Etiquette
{
private string mark;
public string colCod { get; set; }
private string desc;
public Etiquette(string m, string c, string d)
{
mark = m;
colCod = c;
desc = d;
}
}
答案 0 :(得分:2)
您应该将System.Drawing.Bitmap
对象转换为System.Windows.Media.Imaging.BitmapImage
:
Load a WPF BitmapImage from a System.Drawing.Bitmap
...并通过公共属性公开BitmapImage
:
public class Type
{
private string mark;
public string name { get; set; }
private string desc;
private Bitmap bitmap;
public BitmapImage img { get; set; }
public Type(string m, string n, string d, Bitmap mg)
{
mark = m;
name = n;
desc = d;
bitmap = mg;
img = Convert(mg);
}
private static BitmapImage Convert(Bitmap bitmap)
{
BitmapImage bitmapImage;
using (System.IO.MemoryStream memory = new System.IO.MemoryStream())
{
bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
memory.Position = 0;
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
return bitmapImage;
}
}
然后你的绑定应该有效。您无法直接绑定到System.Drawing.Bitmap
。
答案 1 :(得分:0)