当前位置: 代码迷 >> 综合 >> WPF 绑定实例之 LISTBOX显示 图片列表
  详细解决方案

WPF 绑定实例之 LISTBOX显示 图片列表

热度:62   发布时间:2024-01-15 21:48:49.0

WPF  listbox  绑定实例 显示 图片列表

XAML:



[csharp]  view plain copy print ?
  1. <StackPanel>  
  2.        <ListBox x:Name="lstImgs">  
  3.            <ListBox.ItemTemplate>  
  4.                <DataTemplate>  
  5.                    <Image Width="100" Height="30" Source="{Binding Path=FullPath}">  
  6.                          
  7.                    </Image>  
  8.                </DataTemplate>  
  9.            </ListBox.ItemTemplate>  
  10.        </ListBox>  
  11.    </StackPanel>  




CS:


   
[csharp]  view plain copy print ?
  1. public class Photo  
  2.    {  
  3.        public string FullPath { get; set; }  
  4.    }  
  5.   
  6.   
  7.        public MainWindow()  
  8.        {  
  9.            InitializeComponent();  
  10.            this.InitPhoto();  
  11.        }  
  12.        public List<Photo> photos = new List<Photo>();  
  13.   
  14.   
  15.        private void InitPhoto()  
  16.        {  
  17.   
  18.   
  19.            System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();  
  20.            fbd.ShowDialog();  
  21.            string rootPath = fbd.SelectedPath;  
  22.            //MessageBox.Show(rootPath);  
  23.            GetAllImagePath(rootPath);  
  24.            lstImgs.ItemsSource = photos;  
  25.   
  26.   
  27.        }  
  28.         public void GetAllImagePath(string path)  
  29.        {  
  30.            DirectoryInfo di = new DirectoryInfo(path);  
  31.            FileInfo[] files = di.GetFiles("*.*", SearchOption.AllDirectories);  
  32.   
  33.   
  34.            if (files != null && files.Length > 0)  
  35.            {  
  36.                foreach (var file in files)  
  37.                {  
  38.                    if (file.Extension==(".jpg") ||  
  39.                        file.Extension == (".png") ||  
  40.                        file.Extension == (".bmp") ||  
  41.                        file.Extension == (".gif"))  
  42.                    {  
  43.                        photos.Add(new Photo()  
  44.                        {  
  45.                            FullPath = file.FullName  
  46.                        });  
  47.                    }  
  48.                }  
  49.            }  
  50.        }