我已经搜索了很多,但没有得到我想要的。我需要用图像填充一个组合框(嵌入在 Resources.resx 中的 114 张图像(。
我只是得到列表,而不是图像。这是我的代码。
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"/>
使用项模板最简单。为此,我们定义一个带有DataType
String
的DataTemplate
并将其设置为 ComboBox.ItemTemplate
.为了在 XAML 中使用String
,我们需要引用xmlns:system="clr-namespace:System;assembly=mscorlib"
程序集和命名空间。对于绑定,我们使用一个ObservableCollection<string>
来保存图像的相对路径:
查看型号:
public class ViewModel : INotifyPropertyChanged
{
public TestViewModel()
{
this.ImageSources = new ObservableCollection<string>() { @"ResourcesIconsimage.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
,而是可以将初始化移动到其他任何位置。