如果这很简单,我会有点沮丧...
我有大约120张图片,当组合框中的名称对应于该图片时,我希望能够选择并显示其中一张图片。我想知道如何使用每张图片的名称填充组合框并从框中选择一张图片而不制作120“if”语句?每个图像在project.Properties.Resources文件夹中都有自己的文件名
另外,如果有一种方法可以非常快速地重命名120张图片,那将节省我很多时间,但如果我只需要亲手操作就可以了。
表单是WPF,我正在使用Visual Studio 2012 Express
答案 0 :(得分:3)
您可以创建Model
来保存图片数据并填充该模型的ObservableCollection<T>
,然后我们可以将该集合绑定到ComboBox
并设置ComboBox
selectedItem为Image
控件
以下是一个例子:
代码:
namespace WpfApplication14
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private ObservableCollection<MyImage> _images = new ObservableCollection<MyImage>();
private MyImage _selectedImage;
public MainWindow()
{
InitializeComponent();
// Add image files to collection
foreach (var image in Directory.GetFiles(@"C:\your image directory"))
{
// set name and path in model
Images.Add(new MyImage { Path = image, Name = System.IO.Path.GetFileNameWithoutExtension(image) });
}
}
public ObservableCollection<MyImage> Images
{
get { return _images; }
set { _images = value; }
}
public MyImage SelectedImage
{
get { return _selectedImage; }
set { _selectedImage = value; NotifyPropertyChanged("SelectedImage"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
public class MyImage
{
public string Name { get; set; }
public string Path { get; set; }
}
}
的Xaml:
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Name="UI">
<StackPanel DataContext="{Binding ElementName=UI}">
<TextBlock Text="Images" />
<ComboBox ItemsSource="{Binding Images}" SelectedItem="{Binding SelectedImage}" DisplayMemberPath="Name"/>
<TextBlock Text="Selected Image" />
<Image Source="{Binding SelectedImage.Path}" />
</StackPanel>
</Window>
结果:
答案 1 :(得分:0)
好WPF
内存真的很生疏,但作为概括,您需要知道列表中所选图像的位置。你可以做的是跟踪字典中列表中每个图像的索引/位置:
private imageIndices=new Dictionary<string, int>();
商店指数:
imageIndices[<IMAGE_NAME>] = <INDEX_OF_IMAGE>;
从下拉列表中获取图像名称,并从字典中获取该图像的位置:
var n=<IMAGE_NAME>;
list.Select(imageIndices[<IMAGE_NAME>]);//use actual method name to select