本文使用WPF窗体(XAML及C#)与Win Form控件(FolderBrowserDialog)结合的方式, 演示制作了一个简易漂亮的WPF图片浏览器。
首先看看运行中的样子:
XAML源码:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="684" Width="643">
对应的C#源码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace BrawDraw.Com.FilmEffect
{
///
/// Interaction logic for PhotoViewer.xaml
///
public partial class PhotoViewer : Window
{
public PhotoViewer()
{
InitializeComponent();
}
string selectedPath = string.Empty;
string getFilesFilter = "*.jpg;*.jpeg;*.jpe;*.gif;*.bmp;*.png;";
private void btnSelectFolder_Click(object sender, RoutedEventArgs e)
{
// 这里使用了Window Forms中的文件夹选取对话框
FolderBrowserDialog dlgFolder = new FolderBrowserDialog();
dlgFolder.SelectedPath = @"C:\Photo_Frame\BurnedDisk";
dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;
if (System.Windows.Forms.DialogResult.OK == dlgFolder.ShowDialog())
{
selectedPath = dlgFolder.SelectedPath;
// 使用OpenFilesDirs()读取选定文件夹下的所有图片,如果选择包含子目录,则同时读入所有子目录的图片
OpenFilesDirs(selectedPath);
}
}
private void OpenFilesDirs(string openFilePath)
{
string[] arrDirs = Directory.GetDirectories(openFilePath);
string[] arrFilter = getFilesFilter.Split(';');
System.IO.DirectoryInfo dirInfo =
new System.IO.DirectoryInfo(openFilePath);
for (int i = 0; i < arrFilter.Length; i++)
{
System.IO.FileInfo[] files = dirInfo.GetFiles(arrFilter[i]);
if (files != null)
{
foreach (System.IO.FileInfo file in files)
{
listBoxPhotos.Items.Add(file.FullName);
}
}
}
if ((bool)rBtnIncludeChild.IsChecked)
{
if (arrDirs.Length != 0)
{
for (int i = 0; i < arrDirs.Length; i++)
{
// 递归读取子目录
OpenFilesDirs(openFilePath + "\\" + System.IO.Path.GetFileName(arrDirs[i]));
}
}
else
return;
}
}
private void listBoxPhotos_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// 由于有些图片暂时仍无法使用WPF的图片解码器进行读取,所以以下的try{}catch(){}语句是必要的
try
{
imageBox.Source = new BitmapImage(new Uri(listBoxPhotos.SelectedValue.ToString(), UriKind.RelativeOrAbsolute));
}
catch (Exception exc)
{
// 这里使用了一个WPF Window进行错误显示, 如有时间的话, 还可以把它做得更漂亮些.
Window win = new Window();
win.Title = "Error!";
win.Content = exc.Message + ". File name is " + listBoxPhotos.SelectedValue.ToString() ;
win.ShowDialog();
}
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/14601556/viewspace-528543/ ,如需转载,请注明出处,否则将追究法律责任。