Barzo Barzo - 1 year ago 199
C# Question

WPF ComboBox with image

I'm trying to populate a Combo with images. It is defined as:

<ComboBox SelectedItem="{Binding SelectedLangComboItem}"
ItemsSource="{Binding Languages}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Image}" />
<TextBlock Text="{Binding Label}" />

Where the items are the LanguageItem classes:

public class LanguageItem
public System.Drawing.Bitmap Image { get; set; }
public string Label { get; set; }
public string Culture { get; set; }

public LanguageItem(System.Drawing.Bitmap image, string label, string culture)
Image = image;
Label = label;
Culture = culture;

Now, in my ViewModel c'tor I do:

_Languages = new ObservableCollection<LanguageItem>();

System.Reflection.Assembly app = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file;
file = app.GetManifestResourceStream("MyNamespace.Images.FLAG1.gif");
_Languages.Add(new LanguageItem(new Bitmap(file), "ITALIAN", "it-IT"));
file = app.GetManifestResourceStream("MyNamespace.Images.FLAG2.gif");
_Languages.Add(new LanguageItem(new Bitmap(file), "ENGLISH", "en-EN"));

this.SelectedLangItem = _Languages[0];

The images are embedded resources. Here I have two problems:

  1. The images are not displayed;

  2. The Item is not selected, the SelectedLangItem is:

    public LanguageItem SelectedLangItem
    get { return _SelectedLangItem; }
    if (_SelectedLangItem == value)

    _SelectedLangItem = value;

Answer Source


new BitmapImage(new Uri("MyNamespace.Images.FLAG1.gif", UriKind.Relative));

as it have to implement ImageSource

And regarding not selected: Property name is "SelectedLangItem" while in xaml SelectedLangComboItem if you did not mistype.




<ComboBox SelectedItem="{Binding SelectedLangComboItem}"