WPF中簡單的圖片瀏覽功能
阿新 • • 發佈:2019-02-13
廢話不說直接上程式碼:
/// <summary> /// MainWindow.xaml 的互動邏輯 /// </summary> public partial class MainWindow : Window { ObservableCollection<BitmapImage> bmList; int index = 0; //記錄索引 BackgroundWorker bw = new BackgroundWorker(); public MainWindow() { InitializeComponent(); InitList(); CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering); bw.DoWork += new DoWorkEventHandler(bw_DoWork); button1.Click += new RoutedEventHandler(button1_Click); button2.Click += new RoutedEventHandler(button2_Click); button3.Click += new RoutedEventHandler(button3_Click); } void button2_Click(object sender, RoutedEventArgs e) { if (index < bmList.Count - 1) index++; else index = 0; } void button1_Click(object sender, RoutedEventArgs e) { if (index > 0) index--; else index = bmList.Count - 1; } bool flag = true; void button3_Click(object sender, RoutedEventArgs e) { if (flag == true) { bw.RunWorkerAsync(); flag = false; (sender as Button).Content = "End"; } else { flag = true; (sender as Button).Content = "Start"; } } void bw_DoWork(object sender, DoWorkEventArgs e) { while (!e.Cancel) { button2_Click(sender, new RoutedEventArgs()); System.Threading.Thread.Sleep(2000); //停2秒 e.Cancel = flag; } } List<string> list = new List<string>(); public void InitList() { list = System.IO.Directory.GetFiles("../../Image/").ToList(); bmList = new ObservableCollection<BitmapImage>(); for (int i = 1; i < list.Count; i++) { Uri url = new Uri(list[i].Substring(5), UriKind.Relative); BitmapImage bmImg = new BitmapImage(url); bmList.Add(bmImg); } } void CompositionTarget_Rendering(object sender, EventArgs e) { this.imgViewer.Source = bmList[index]; label1.Content = index.ToString(); this.imgViewer.Width = this.imgViewer.Source.Width; this.imgViewer.Height = this.imgViewer.Source.Height; } }
效果圖如下:
如果單擊start按鈕,程式會自動瀏覽圖片。
如果單擊左右按鈕,可以手動瀏覽。