WPF press keydown and show image one by one

//xaml
<Window x:Class="WpfApp175.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:WpfApp175" KeyDown="Window_KeyDown"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Image x:Name="img" ClipToBounds="True" />
    </Grid>
</Window>


//xaml.cs
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp175
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent(); 
            this.DataContext = this;
            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var imgsList = System.IO.Directory.GetFiles(@"..\..\Images").OrderByDescending(x => x.Length).ToList();
            ImgsList = new List<string>(imgsList);
            img.Source = new BitmapImage(new Uri(ImgsList[ImgIndex], UriKind.RelativeOrAbsolute));
            ImgsCount = ImgsList.Count;
        }
         
        public List<string> ImgsList = new List<string>();
        public int ImgsCount { get; set; }
        public int ImgIndex { get; set; } = 0;        

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key==Key.Down)
            { 
                img.Source = new BitmapImage(new Uri(ImgsList[ImgIndex], UriKind.RelativeOrAbsolute));
                ++ImgIndex;
                if (ImgIndex >= ImgsCount)
                {
                    ImgIndex = 0;
                }
            } 
        }
    }
}

 

posted @ 2024-06-16 22:12  FredGrit  阅读(3)  评论(0编辑  收藏  举报