如何在组合框中从Resources.resx添加图像

时间:2019-06-20 15:38:45

标签: c# wpf

我进行了很多搜索,但无法获得想要的东西。我需要用图像填充一个组合框(114个图像嵌入Resources.resx中)。

我只是得到列表,而不是图像。这是我的代码。

ResourceSet rsrcSet =MyProject.Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);

            List<object> images = new List<object>();

            foreach (DictionaryEntry entry in rsrcSet)
            {
                //String name = entry.Key.ToString();
                //Object resource = entry.Value;
                images.Add( Don't know what will be here? );
            }

            var comboBox = sender as ComboBox;

            comboBox.ItemsSource = images;

和我的XAML

                <ComboBox HorizontalAlignment="Left" Grid.Column="0" Grid.Row="0" VerticalAlignment="Top" Width="320" Loaded="ComboBox_Loaded" SelectionChanged="ComboBox_SelectionChanged"/>

1 个答案:

答案 0 :(得分:1)

使用项目模板最简单。为此,我们用DataTemplate DataType定义了String并将其设置为ComboBox.ItemTemplate。为了在XAML中使用String,我们需要引用xmlns:system="clr-namespace:System;assembly=mscorlib"程序集和名称空间。对于绑定,我们使用ObservableCollection<string>来保存图像的相对路径:

查看模型:

public class ViewModel : INotifyPropertyChanged
{
    public TestViewModel()
    {
      this.ImageSources = new ObservableCollection<string>() { @"Resources\Icons\image.png" };      
    }

    /// <summary>
    /// Event fired whenever a child property changes its value.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Method called to fire a <see cref="PropertyChanged"/> event.
    /// </summary>
    /// <param name="propertyName"> The property name. </param>
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private ObservableCollection<string> imageSources;   
    public ObservableCollection<string> ImageSources
    {
      get => this.imageSources;
      set 
      { 
        this.imageSources = value; 
        OnPropertyChanged();
      }
    }
}

Xaml:

<Window x:Class="MainWindow" 
    xmlns:system="clr-namespace:System;assembly=mscorlib">
  <Window.DataContext>
     <viewModels:ViewModel />
  </Window.DataContext>
  <Window.Resources>
      <DataTemplate x:Key="ComboBoxItemTemplate" DataType="system:String">
            <Image Source="{Binding}" Height="100" Width="100"/>
      </DataTemplate>
  </Window.Resources>
  <Grid>
    <StackPanel>
      <ComboBox ItemTemplate="{StaticResource ComboBoxItemTemplate}"
                ItemsSource="{Binding ImageSources}" />
    </StackPanel>
  </Grid>
</Window>

要使其工作,词典应包含相对的图像路径。如果不是,您必须转换。因此,无需像在示例中那样在构造函数中初始化ObservableCollection,您可以将初始化移动到其他任何地方。