c# – 带图像的WPF ComboBox

我正在尝试使用图像填充组合.它被定义为:

<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>

项目是LanguageItem类:

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;
  }
}

现在,在我的ViewModel c’tor中,我做了:

  _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];

图像是嵌入的资源.我有两个问题:

>不显示图像;
>未选择项目,SelectedLangItem为:

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

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

解决方法:

使用

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

因为它必须实现ImageSource

并且未选中:如果您没有错误输入,则在xaml SelectedLangComboItem中,属性名称为“SelectedLangItem”.

码:

this.RaisePropertyChanged("SelectedLangItem");

XAML:

<ComboBox SelectedItem="{Binding SelectedLangComboItem}"
上一篇:如何在WPF C#中使用组合框AddRange


下一篇:c# – 设置ComboBox默认值而不直接更改SelectedIndex