首页 > 其他分享 >WPF ListBox ListBoxItemTemplate display image automatically via System.Timers.Timer

WPF ListBox ListBoxItemTemplate display image automatically via System.Timers.Timer

时间:2024-10-03 22:00:51浏览次数:7  
标签:via Windows image System private bk using public

//xaml
<Window x:Class="WpfApp6.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:WpfApp6"
        mc:Ignorable="d"
        WindowState="Maximized"
        WindowStyle="None"
        KeyDown="Window_KeyDown"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox x:Name="lbx" 
                 ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 SelectedItem="{Binding SelectedBook,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 VirtualizingPanel.IsContainerVirtualizable="True"
                 VirtualizingPanel.IsVirtualizing="True"
                 VirtualizingPanel.CacheLengthUnit="Item"
                 VirtualizingPanel.VirtualizationMode="Recycling"
                 SelectionChanged="lbx_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding DataContext.ImgUrl,RelativeSource={RelativeSource 
                        Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}}"
                        Width="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
                        Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
                        />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <TextBlock HorizontalAlignment="Right" 
                   VerticalAlignment="Bottom"
                   Width="150"
                   FontSize="50"
                   Foreground="Red"
                   x:Name="tbk"/>
    </Grid>
</Window>


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

namespace WpfApp6
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            //RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.Default;
            this.DataContext = this;
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            tbk.Text = "1";
            BooksCollection = new ObservableCollection<Book>();
            var imgsList = Directory.GetFiles(@"../../Images");
            if (imgsList != null && imgsList.Any())
            {
                int imgsCount = imgsList.Count();
                for (int i = 0; i < 100; i++)
                {
                    BooksCollection.Add(new Book()
                    {
                        Id = i + 1,
                        Name = $"Name_{i + 1}",
                        ImgUrl = imgsList[i % imgsCount],
                    });
                }
            }
            System.Timers.Timer tmr = new System.Timers.Timer();
            tmr.Interval = 100;
            tmr.Elapsed += Tmr_Elapsed;
            tmr.Start();
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
        }

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

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

        private ObservableCollection<Book> books;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return books;
            }
            set
            {
                if(value!=books)
                {
                    books = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }

        private void Tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                if (++lbx.SelectedIndex >= lbx.Items.Count)
                {
                    lbx.SelectedIndex = 0;
                }
                var bk= BooksCollection[lbx.SelectedIndex];
                if (bk!=null)
                {
                    tbk.Text = bk.Id.ToString();
                    SelectedBook = bk;
                    lbx.ScrollIntoView(SelectedBook);
                }
            }));
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.C)
            {
                var msgResult = MessageBox.Show("Are you sure to exit?", "Exit", MessageBoxButton.YesNo,
                    MessageBoxImage.Question, MessageBoxResult.Yes);
                if (msgResult == MessageBoxResult.Yes)
                {
                    Application.Current.Shutdown();
                }
            }
        }

        private void lbx_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(e.AddedItems!=null && e.AddedItems.Count>0)
            {
                var bk = e.AddedItems[0] as Book;
                if (bk!=null)
                {
                    SelectedBook = bk;
                    lbx.ScrollIntoView(SelectedBook);
                }
            }
        }
    }

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

        public string Name { get; set; }

        public string ImgUrl { get; set; }
    }
}

 

 

 

标签:via,Windows,image,System,private,bk,using,public
From: https://www.cnblogs.com/Fred1987/p/18446066

相关文章

  • WPF Datagrid display via DataGridTemplateColumn
    <DataGridTemplateColumnHeader="Image"><DataGridTemplateColumn.CellTemplate><DataTemplate><ImageSource="{BindingDataContext.ImgUrl,RelativeSource={RelativeSourceMode=F......
  • Docker容器Centos不能使用systemctl命令问题
    最近使用Docker搭建Centos容器时遇到这样的问题:Centos系统的不能使用systemctl命令!具体场景使用systemctl或service命令重启服务时。systemctlrestartsnmpd.service会报无权限的错误:FailedtogetD-Busconnection:Operationnotpermitted;这是docker中centos7......
  • WPF FindResource,Resource[key] SystemColors TryFindResource
    //xaml<Windowx:Class="WpfApp3.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.micr......
  • WPF image via web url or uri
    Thebasicroadmapistodownloadwebimageatfirst,second convertitintomemeorystream,thirdassignthememorystreamtobitmapimageasStreamSource. //xaml<Windowx:Class="WpfApp2.MainWindow"xmlns="http://schemas.micro......
  • WPF Click Window show XY coordinates in MVVM via InvokeCommandAction of behavior
    1.Install Microsoft.Xaml.Behaviors.Wpf  2.<behavior:Interaction.Triggers><behavior:EventTriggerEventName="MouseDown"><behavior:InvokeCommandActionCommand="{BindingClickCommand}"......
  • COMP3230 Principles of Operating Systems
    COMP3230PrinciplesofOperatingSystemsProgrammingAssignmentOneDuedate:Oct.17,2024,at23:59Total13points–ReleaseCandidateVersion2ProgrammingExercise–ImplementaLLMChatbotInterfaceObjectivesAnassessmenttaskrelatedto......
  • Cornell University's Textbook Reading Systems(教科书阅读系统-康奈尔大学)
    TextbookReadingSystemsTextbookreadingsystemshelpyouinteractwiththeinformationintextbookssothatyoucanbetterinternalizeandlearnSQ3RTheSQ3Risasystematicmethoddesignedforstudyingatextbook.DevelopedbyFrancisP.Robinson,......
  • System.out.printf
    程序示例:importjava.util.Scanner;publicclassTest{publicstaticvoidmain(String[]args){System.out.print("请输入你的名字:");Scannerin=newScanner(System.in);Stringname=in.nextLine();System.out.print(&......
  • 【常用API】Math,System,Runtime,BigDecimal
    Math代表数学,是一个工具类,提供的都是对数据进行操作的一些静态方法。Math类提供的常见方法方法名说明publicstaticintabs(inta)获取参数的绝对值publicstaticdoubleceil(doublea)向上取整publicstaticdoublefloor(doublea)向下取整publicstaticintround(......
  • 怎么解决os.system中Program Files中空格报错的问题
    在通过os.system(PATH)时由于c盘中的ProgramFiles之间带有空格,从而导致在识别时会识别到Program时停止从而产生报错例如:os.system('C:\ProgramFiles(x86)\Microsoft\Edge\Application\msedge.exe')通过网上查找原因,大部分都是说加上双引号就行了我以为是:"C:\ProgramF......