Search code examples
c#wpfcombobox

WPF ComboBox with image


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

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

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; } set { if (_SelectedLangItem == value) return;

        _SelectedLangItem = value;
        this.RaisePropertyChanged("SelectedLangItem");
      }
    }
    

Solution

  • Use

    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.

    CODE:

    this.RaisePropertyChanged("SelectedLangItem");
    

    XAML:

    <ComboBox SelectedItem="{Binding SelectedLangComboItem}"