加载目录下的图片并选择展示

clipboard.png
实现功能有:

  1. 选择目录,加载图片
  2. 选择图片,展示

难点:

  1. WPF下选择目录,并加载到集合
  2. 绑定到集合当前项

主要思路及关键代码:
一个数据模板类Photo,更简单的就利用库里的BitmapFrame类。

public class Photo
    {
        private readonly Uri _source;

        public Photo(string path)
        {
            Source = path;
            _source = new Uri(path);
            Image = BitmapFrame.Create(_source);
            //Metadata = new ExifMetadata(_source);
        }

        public string Source { get; }
        public BitmapFrame Image { get; set; }
        //public ExifMetadata Metadata { get; }

        public override string ToString() => _source.ToString();
    }

一个视图模型类PhotoCollection集合类,继承ObservableCollection<Photo>,作为绑定源。
此时需要注意:

  1. 重新选择目录是需要更新集合Update()
/// <summary>
    ///     This class represents a collection of photos in a directory.
    /// </summary>
    public class PhotoCollection : ObservableCollection<Photo>
    {
        private DirectoryInfo _directory;

        public PhotoCollection()
        {
        }

        public PhotoCollection(string path) : this(new DirectoryInfo(path))
        {
        }

        public PhotoCollection(DirectoryInfo directory)
        {
            _directory = directory;
            Update();
        }

        public string Path
        {
            set
            {
                _directory = new DirectoryInfo(value);
                Update();
            }
            get { return _directory.FullName; }
        }

        public DirectoryInfo Directory
        {
            set
            {
                _directory = value;
                Update();
            }
            get { return _directory; }
        }

        private void Update()
        {
            Clear();
            try
            {
                foreach (var f in _directory.GetFiles("*.jpg"))
                    Add(new Photo(f.FullName));
            }
            catch (DirectoryNotFoundException)
            {
                MessageBox.Show("No Such Directory");
            }
        }
    }

视图MainWindow类

  1. 其中使用了一个数据模板作为主图片区,使用ListBox的当前选定项作为绑定源,绑定Photo类的BitmapFrame属性
  2. Grid的数据上下文DataContext绑定共享App资源:视图模型类PhotoCollection,
<Window x:Class="PhotoViewDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PhotoViewDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="825"
        Loaded="OnLoaded"
        >
    <Window.Resources>
        <DataTemplate x:Key="MainImageTemplate">
            <Border BorderBrush="LimeGreen" BorderThickness="5">
                <Image Source="{Binding Path=Image}"/>
            </Border>
        </DataTemplate>        
    </Window.Resources>
    <Grid DataContext="{Binding Source={StaticResource Photos}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition MaxWidth="250"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="25"/>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <DockPanel LastChildFill="True" >
            <TextBlock DockPanel.Dock="Left" VerticalAlignment="Center">目录:</TextBlock>            
            <Button x:Name="_btSelectedFile" HorizontalAlignment="Right" DockPanel.Dock="Right" Content="选择文件" Click="_btSelectedFile_Click"/>
            <TextBox DockPanel.Dock="Left" Name="_tbFile"></TextBox>
        </DockPanel>
        <TextBlock Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center">当前目录的图片类型:</TextBlock>
        <ComboBox Width="50" Grid.Row="1" HorizontalAlignment="Right" ></ComboBox>
        <TextBlock Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" Text="已选图片"/>
        <ScrollViewer Grid.Row="2" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
            <ListBox
                    IsSynchronizedWithCurrentItem="True"
                    Name="PhotosListBox"                    
                    Margin="5"
                    SelectionMode="Single"
                    ItemsSource="{Binding}"
                    SelectedIndex="0"
                    MouseDoubleClick="OnPhotoClick">
                <ListBox.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Edit" Click="EditPhoto" />
                    </ContextMenu>
                </ListBox.ContextMenu>
            </ListBox>
        </ScrollViewer>
        <TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Path=/Directory }"/>
        <ContentControl Content="{Binding Path=/}" ContentTemplate="{StaticResource MainImageTemplate}" Grid.Column="1" Grid.Row="2"/>
    </Grid>
</Window>

后台逻辑:
需要注意的是:

  1. Xaml标识的资源怎么在代码中引用。
  2. WPF没有直接使用的打开目录代码和不能using System.Windows.Forms,此时需要额外利用一个中间类嵌入到WPF中。
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    public PhotoCollection Photos;
    public MainWindow()
    {
        InitializeComponent();            
    }

    private void _btSelectedFile_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
        System.Windows.Interop.HwndSource source = PresentationSource.FromVisual(this) as System.Windows.Interop.HwndSource;
        System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
        System.Windows.Forms.DialogResult result = dlg.ShowDialog(win);
        
        if (result == System.Windows.Forms.DialogResult.OK)
        {
            _tbFile.Text = dlg.SelectedPath;
            Photos.Path = _tbFile.Text;
        }
    }
    private void EditPhoto(object sender, RoutedEventArgs e)
    {

    }
    private void OnPhotoClick(object sender, RoutedEventArgs e)
    {

    }
    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        _tbFile.Text = @"J:\照片记录\火影图片";
        Photos = (PhotoCollection)(Application.Current.Resources["Photos"] as ObjectDataProvider)?.Data;
        Photos.Path = _tbFile.Text;
    }
}
public class OldWindow : System.Windows.Forms.IWin32Window
    {
        IntPtr _handle;
        public OldWindow(IntPtr handle)
        {
            _handle = handle;
        }
        #region IWin32Window Members
        IntPtr System.Windows.Forms.IWin32Window.Handle
        {
            get { return _handle; }
        }
        #endregion
    }

扩展:

  1. ListBox加载太多图片有些卡,此时可以只加载目录路径或图片名称或缩略图,提高性能当选择一项时,利用数据转换再加载大容量的图片,提高响应速度。
  2. 可选择性的加载目录下的不同图片类型,方便使用操作。

具体代码陆续其他章节体现。


李志玮
22 声望34 粉丝

求索~~