WPF listbox 绑定实例 显示 图片列表
XAML:
- <StackPanel>
- <ListBox x:Name="lstImgs">
- <ListBox.ItemTemplate>
- <DataTemplate>
- <Image Width="100" Height="30" Source="{Binding Path=FullPath}">
- </Image>
- </DataTemplate>
- </ListBox.ItemTemplate>
- </ListBox>
- </StackPanel>
CS:
- public class Photo
- {
- public string FullPath { get; set; }
- }
- public MainWindow()
- {
- InitializeComponent();
- this.InitPhoto();
- }
- public List<Photo> photos = new List<Photo>();
- private void InitPhoto()
- {
- System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
- fbd.ShowDialog();
- string rootPath = fbd.SelectedPath;
- //MessageBox.Show(rootPath);
- GetAllImagePath(rootPath);
- lstImgs.ItemsSource = photos;
- }
- public void GetAllImagePath(string path)
- {
- DirectoryInfo di = new DirectoryInfo(path);
- FileInfo[] files = di.GetFiles("*.*", SearchOption.AllDirectories);
- if (files != null && files.Length > 0)
- {
- foreach (var file in files)
- {
- if (file.Extension==(".jpg") ||
- file.Extension == (".png") ||
- file.Extension == (".bmp") ||
- file.Extension == (".gif"))
- {
- photos.Add(new Photo()
- {
- FullPath = file.FullName
- });
- }
- }
- }
- }