WPF MVVM capture window keyboard

 //xaml
    <behavior:Interaction.Triggers>
        <behavior:EventTrigger EventName="KeyDown">
            <behavior:CallMethodAction TargetObject="{Binding}" MethodName="Window_KeyDown"/>
        </behavior:EventTrigger>
    </behavior:Interaction.Triggers>


//cs
public void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space)
    {
        IsPaused = !IsPaused;
    }
}

 

 

 Whole code

//xaml
<Window x:Class="WpfApp197.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:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp197"  
        mc:Ignorable="d" WindowState="Maximized"
        Title="{Binding MainTitle,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Height="450" Width="800">
    <behavior:Interaction.Triggers>
        <behavior:EventTrigger EventName="KeyDown">
            <behavior:CallMethodAction TargetObject="{Binding}" MethodName="Window_KeyDown"/>
        </behavior:EventTrigger>
    </behavior:Interaction.Triggers>
    <Grid Background="Transparent"> 
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox x:Name="lbx" Grid.Column="0" 
                 ItemsSource="{Binding BooksList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 SelectedItem="{Binding SelectedBook,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 SelectedIndex="{Binding SelectedIdx,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding ImgUrl}" Width="200" Height="500"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Image Grid.Column="1" ClipToBounds="True"
               Source="{Binding SelectedItem.ImgUrl,ElementName=lbx}"/>
    </Grid>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
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;
using System.IO;

namespace WpfApp197
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new BookVM();
            this.DataContext = vm;
        }

    }

    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitData();
            TimerChangedImgPeriodically();
        }

        private void TimerChangedImgPeriodically()
        {
            System.Timers.Timer tm = new System.Timers.Timer();
            tm.Interval = 200;
            tm.Elapsed += Tm_Elapsed;
            tm.Start();
        }

        private void Tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!IsPaused)
            {
                if (++SelectedIdx >= BooksList.Count)
                {
                    SelectedIdx = 0;
                }
            }
        }

        private void InitData()
        {
            BooksList = new List<Book>();
            var imgsList = Directory.GetFiles(@"..\..\Images", "*.*");
            int len = imgsList.Length;

            if (imgsList != null && imgsList.Any())
            {
                for (int i = 0; i < len; i++)
                {
                    BooksList.Add(new Book()
                    {
                        Id = i + 1,
                        ImgUrl = imgsList[i % len]
                    });
                }
                SelectedBook = BooksList[0];
            }
        }

        public void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space)
            {
                IsPaused = !IsPaused;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        private List<Book> booksList;
        public List<Book> BooksList
        {
            get
            {
                return booksList;
            }
            set
            {
                if (value != null)
                {
                    booksList = value;
                    OnPropertyChanged(nameof(BooksList));
                }
            }
        }

        private Book selectedBook;
        public Book SelectedBook
        {
            get
            {
                return selectedBook;
            }
            set
            {
                if (value != selectedBook)
                {
                    selectedBook = value;
                    OnPropertyChanged(nameof(SelectedBook));
                    MainTitle = SelectedBook.ImgUrl;
                }
            }
        }

        private string mainTitle;
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged(nameof(MainTitle));
                }
            }
        }

        private int selectedIdx;
        public int SelectedIdx
        {
            get
            {
                return selectedIdx;
            }
            set
            {
                if (value != selectedIdx)
                {
                    selectedIdx = value;
                    OnPropertyChanged(nameof(SelectedIdx));
                }
            }
        }

        private bool isPaused;
        public bool IsPaused
        {
            get
            {
                return isPaused;
            }
            set
            {
                if (value != isPaused)
                {
                    isPaused = value;
                    OnPropertyChanged(nameof(IsPaused));
                    if(IsPaused) 
                    {
                        MainTitle = $"{SelectedBook.ImgUrl} is Paused!";
                    }
                }
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string ImgUrl { get; set; }
    }
}

 

posted @ 2024-07-06 18:10  FredGrit  阅读(5)  评论(0编辑  收藏  举报