WPF render periodically via DispatcherTimer, customize behavior

Install-Package Microsoft.Xaml.Behaviors.Wpf
Install-Package Newtonsoft.json
Install-Package CsvHelper

 

public class GridRightBehavior : Behavior<Grid>
{
    private ContextMenu ctxMenu;
    private MenuItem saveJsonMenuItem;
    private MenuItem saveCSVMenuItem;
    public GridRightBehavior()
    {
        InitContextMenu();
    }

    private void InitContextMenu()
    {
        ctxMenu = new ContextMenu();
        saveJsonMenuItem = new MenuItem()
        {
            Header = "Save Json"
        };
        saveJsonMenuItem.Click += SaveJsonMenuItem_Click;
        saveCSVMenuItem = new MenuItem()
        {
            Header = "Save CSV"
        };
        saveCSVMenuItem.Click += SaveCSVMenuItem_Click;
        ctxMenu.Items.Add(saveJsonMenuItem);
        ctxMenu.Items.Add(saveCSVMenuItem);
    }

    private void SaveCSVMenuItem_Click(object sender, RoutedEventArgs e)
    {
        SaveCSVCommand?.Execute(CmdPara);
    }

    private void SaveJsonMenuItem_Click(object sender, RoutedEventArgs e)
    {
        SaveJsonCommand?.Execute(CmdPara);
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.ContextMenu = ctxMenu;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        DestoryContextMenu();
    }

    private void DestoryContextMenu()
    {
        if(saveJsonMenuItem!=null)
        {
            saveJsonMenuItem.Click-= SaveJsonMenuItem_Click;
            saveJsonMenuItem = null;
        }

        if(saveCSVMenuItem!=null)
        {
            saveCSVMenuItem.Click-= SaveCSVMenuItem_Click;
            saveCSVMenuItem = null;
        }

        if (ctxMenu != null)
        {
            ctxMenu.Items.Clear();
            ctxMenu = null;               
        }
        AssociatedObject.ContextMenu = null;
    }

    public object CmdPara
    {
        get { return (object)GetValue(CmdParaProperty); }
        set { SetValue(CmdParaProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CmdPara.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CmdParaProperty =
        DependencyProperty.Register(nameof(CmdPara), typeof(object),
            typeof(GridRightBehavior), new PropertyMetadata(null));


    public ICommand SaveCSVCommand
    {
        get { return (ICommand)GetValue(SaveCSVCommandProperty); }
        set { SetValue(SaveCSVCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SaveCSVCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SaveCSVCommandProperty =
        DependencyProperty.Register(nameof(SaveCSVCommand), typeof(ICommand),
            typeof(GridRightBehavior), new PropertyMetadata(null));



    public ICommand SaveJsonCommand
    {
        get { return (ICommand)GetValue(SaveJsonCommandProperty); }
        set { SetValue(SaveJsonCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SaveJsonCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SaveJsonCommandProperty =
        DependencyProperty.Register(nameof(SaveJsonCommand), typeof(ICommand), typeof(GridRightBehavior),
            new PropertyMetadata(null));
}


 <behavior:Interaction.Behaviors>
     <local:GridRightBehavior
            SaveCSVCommand="{Binding DataContext.SaveCSVCmd,RelativeSource={RelativeSource AncestorType=Window}}"
            CmdPara="{Binding SelectedItems,RelativeSource={RelativeSource AncestorType=DataGrid}}"
            SaveJsonCommand="{Binding DataContext.SaveJsonCmd,RelativeSource={RelativeSource AncestorType=Window}}"/>   
 </behavior:Interaction.Behaviors>


        public ICommand SaveCSVCmd { get; set; }
        public ICommand SaveJsonCmd { get; set; }

private void InitCommands()
{
    SaveCSVCmd = new DelCommand(SaveCSVCmdExecuted);
    SaveJsonCmd = new DelCommand(SaveJsonCmdExecuted);
}

private void SaveJsonCmdExecuted(object? obj)
{
    var selectedItems = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
    if (selectedItems != null && selectedItems.Any())
    {
        string jsonFile = $"Json_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
        string jsonStr=JsonConvert.SerializeObject(selectedItems, Formatting.Indented);
        if(!string.IsNullOrWhiteSpace(jsonStr))
        {
            using(StreamWriter jsonWriter=new StreamWriter(jsonFile,false,Encoding.UTF8))
            {
                jsonWriter.WriteLine(jsonStr);
                MessageBox.Show($"Save {selectedItems.Count()} items in Json {jsonFile}", $"Json File,{DateTime.Now}");
            }
        }
    }
}

private void SaveCSVCmdExecuted(object? obj)
{
    var selectedItems = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
    if (selectedItems != null && selectedItems.Any())
    {
        string csvFile = $"CSV_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.csv";
        using(StreamWriter fsWriter=new StreamWriter(csvFile,false,Encoding.UTF8))
        {
            CsvHelper.CsvWriter csvWriter = new CsvHelper.CsvWriter(fsWriter, CultureInfo.InvariantCulture);
            csvWriter.WriteRecords(selectedItems);
            MessageBox.Show($"Save {selectedItems.Count()} items in CSV {csvFile}", $"CSV File,{DateTime.Now}");
        }                
    }
}

 

 

 

<Window x:Class="WpfApp28.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:WpfApp28"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.Resources>
        <local:ImgUrlConverter x:Key="ImgUrlConverter"/>
    </Window.Resources>
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection}"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="2,2"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  ScrollViewer.CanContentScroll="True"
                  EnableColumnVirtualization="True"
                  EnableRowVirtualization="True"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False"
                  AlternatingRowBackground="AliceBlue"
                  AlternationCount="2"
                  SnapsToDevicePixels="True"
                  UseLayoutRounding="True"
                  SelectionMode="Extended"
                  >
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid Width="{x:Static SystemParameters.FullPrimaryScreenWidth}"
                                  Height="{x:Static SystemParameters.FullPrimaryScreenHeight}">
                                <Grid.Background>
                                    <ImageBrush ImageSource="{Binding ImgUrl,Converter={StaticResource ImgUrlConverter}}"
                                                Stretch="Uniform"/>
                                </Grid.Background>
                                <Grid.Resources>
                                    <Style TargetType="TextBlock">
                                        <Setter Property="FontSize" Value="30"/>
                                        <Style.Triggers>
                                            <Trigger Property="IsMouseOver" Value="True">
                                                <Setter Property="FontSize" Value="50"/>
                                                <Setter Property="Foreground" Value="Red"/>
                                            </Trigger>
                                        </Style.Triggers>
                                    </Style>
                                </Grid.Resources>
                                <Grid.RowDefinitions>
                                    <RowDefinition/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>                               
                                <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Id}"/>
                                <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>
                                <TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding ISBN}"/>
                                <behavior:Interaction.Behaviors>
                                    <local:GridRightBehavior
                                           SaveCSVCommand="{Binding DataContext.SaveCSVCmd,RelativeSource={RelativeSource AncestorType=Window}}"
                                           CmdPara="{Binding SelectedItems,RelativeSource={RelativeSource AncestorType=DataGrid}}"
                                           SaveJsonCommand="{Binding DataContext.SaveJsonCmd,RelativeSource={RelativeSource AncestorType=Window}}"/>   
                                </behavior:Interaction.Behaviors>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


using Microsoft.Xaml.Behaviors;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
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.Windows.Threading;
using Newtonsoft.Json;

namespace WpfApp28
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        private DispatcherTimer tmr;
        private static long idx = 0;
        public ICommand SaveCSVCmd { get; set; }
        public ICommand SaveJsonCmd { get; set; }

        public MainVM()
        {
            Task.Run(async () =>
            {
                await InitBooksCollection();
            });
            InitCommands();
            InitTimer();
        }

        private void InitCommands()
        {
            SaveCSVCmd = new DelCommand(SaveCSVCmdExecuted);
            SaveJsonCmd = new DelCommand(SaveJsonCmdExecuted);
        }

        private void SaveJsonCmdExecuted(object? obj)
        {
            var selectedItems = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if (selectedItems != null && selectedItems.Any())
            {
                string jsonFile = $"Json_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
                string jsonStr=JsonConvert.SerializeObject(selectedItems, Formatting.Indented);
                if(!string.IsNullOrWhiteSpace(jsonStr))
                {
                    using(StreamWriter jsonWriter=new StreamWriter(jsonFile,false,Encoding.UTF8))
                    {
                        jsonWriter.WriteLine(jsonStr);
                        MessageBox.Show($"Save {selectedItems.Count()} items in Json {jsonFile}", $"Json File,{DateTime.Now}");
                    }
                }
            }
        }

        private void SaveCSVCmdExecuted(object? obj)
        {
            var selectedItems = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if (selectedItems != null && selectedItems.Any())
            {
                string csvFile = $"CSV_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.csv";
                using(StreamWriter fsWriter=new StreamWriter(csvFile,false,Encoding.UTF8))
                {
                    CsvHelper.CsvWriter csvWriter = new CsvHelper.CsvWriter(fsWriter, CultureInfo.InvariantCulture);
                    csvWriter.WriteRecords(selectedItems);
                    MessageBox.Show($"Save {selectedItems.Count()} items in CSV {csvFile}", $"CSV File,{DateTime.Now}");
                }                
            }
        }

        private void InitTimer()
        {

            tmr = new DispatcherTimer();
            tmr.Tick += async (s, e) =>
            {
                await InitBooksCollection();
            };
            tmr.Interval = TimeSpan.FromSeconds(30);
            tmr.Start();
        }

        private static long GetIncrementIdx()
        {
            return Interlocked.Increment(ref idx);
        }

        private async Task InitBooksCollection(int cnt = 1000000)
        {
            var imgDir = @"../../../Images";
            if (!Directory.Exists(imgDir))
            {
                return;
            }
            var imgs = Directory.GetFiles(imgDir);
            if (imgs == null || !imgs.Any())
            {
                return;
            }

            int imgsCnt = imgs.Count();
            BooksCollection = new ObservableCollection<Book>();
            List<Book> booksList = new List<Book>();
            for (int i = 0; i < cnt; i++)
            {
                long a = GetIncrementIdx();
                booksList.Add(new Book()
                {
                    Id = a,
                    Name = $"Name_{a}",
                    ISBN = $"ISBN_{a}_{Guid.NewGuid():N}",
                    ImgUrl = $"{imgs[i % imgsCnt]}"
                });

                if (i % 100000 == 0)
                {
                    await PopulateBooksCollectionAsync(booksList);
                }
            }

            if (booksList.Any())
            {
                await PopulateBooksCollectionAsync(booksList);
            }
        }

        private async Task PopulateBooksCollectionAsync(List<Book> booksList)
        {
            var tempList = booksList.ToList();
            booksList.Clear();
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                foreach (var bk in tempList)
                {
                    BooksCollection.Add(bk);
                }
                MainTitle = $"{DateTime.Now},loaded {BooksCollection.Count} books,First id:{BooksCollection.FirstOrDefault()?.Id},Last Id:{BooksCollection.LastOrDefault()?.Id},{GetMem()}";
            }, DispatcherPriority.Background);
        }

        private string GetMem()
        {
            return $"memory:{System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024:N2} M";
        }

        private string mainTitle = $"{DateTime.Now},loading...";
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged();
                }
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if (value != booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged();
                }
            }
        }
        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }

    public class ImgUrlConverter : IValueConverter
    {
        Dictionary<string, ImageSource> imgCache = new Dictionary<string, ImageSource>();
        private readonly object objLock = new object();
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string imgUrl = value?.ToString();
            if (string.IsNullOrWhiteSpace(imgUrl) || !File.Exists(imgUrl))
            {
                return null;
            }

            lock (objLock)
            {
                if (imgCache.TryGetValue(imgUrl, out ImageSource imageSource) && imageSource != null)
                {
                    return imageSource;
                }

                using (FileStream fs = new FileStream(imgUrl, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BitmapImage bmi = new BitmapImage();
                    bmi.BeginInit();
                    bmi.StreamSource = fs;
                    bmi.CacheOption = BitmapCacheOption.OnLoad;
                    bmi.EndInit();
                    if (bmi.CanFreeze)
                    {
                        bmi.Freeze();
                    }
                    imgCache.TryAdd(imgUrl, bmi);
                    return bmi;
                }
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public class DelCommand : ICommand
    {
        private Action<object?>? execute;
        private Predicate<object?>? canExecute;
        public DelCommand(Action<object?>? executeValue, Predicate<object?>? canExecuteValue = null)
        {
            execute = executeValue ?? throw new NullReferenceException(nameof(execute));
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object? parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            execute?.Invoke(parameter);
        }
    }

    public class GridRightBehavior : Behavior<Grid>
    {
        private ContextMenu ctxMenu;
        private MenuItem saveJsonMenuItem;
        private MenuItem saveCSVMenuItem;
        public GridRightBehavior()
        {
            InitContextMenu();
        }

        private void InitContextMenu()
        {
            ctxMenu = new ContextMenu();
            saveJsonMenuItem = new MenuItem()
            {
                Header = "Save Json"
            };
            saveJsonMenuItem.Click += SaveJsonMenuItem_Click;
            saveCSVMenuItem = new MenuItem()
            {
                Header = "Save CSV"
            };
            saveCSVMenuItem.Click += SaveCSVMenuItem_Click;
            ctxMenu.Items.Add(saveJsonMenuItem);
            ctxMenu.Items.Add(saveCSVMenuItem);
        }

        private void SaveCSVMenuItem_Click(object sender, RoutedEventArgs e)
        {
            SaveCSVCommand?.Execute(CmdPara);
        }

        private void SaveJsonMenuItem_Click(object sender, RoutedEventArgs e)
        {
            SaveJsonCommand?.Execute(CmdPara);
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.ContextMenu = ctxMenu;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            DestoryContextMenu();
        }

        private void DestoryContextMenu()
        {
            if(saveJsonMenuItem!=null)
            {
                saveJsonMenuItem.Click-= SaveJsonMenuItem_Click;
                saveJsonMenuItem = null;
            }

            if(saveCSVMenuItem!=null)
            {
                saveCSVMenuItem.Click-= SaveCSVMenuItem_Click;
                saveCSVMenuItem = null;
            }

            if (ctxMenu != null)
            {
                ctxMenu.Items.Clear();
                ctxMenu = null;               
            }
            AssociatedObject.ContextMenu = null;
        }

        public object CmdPara
        {
            get { return (object)GetValue(CmdParaProperty); }
            set { SetValue(CmdParaProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CmdPara.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CmdParaProperty =
            DependencyProperty.Register(nameof(CmdPara), typeof(object),
                typeof(GridRightBehavior), new PropertyMetadata(null));


        public ICommand SaveCSVCommand
        {
            get { return (ICommand)GetValue(SaveCSVCommandProperty); }
            set { SetValue(SaveCSVCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SaveCSVCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SaveCSVCommandProperty =
            DependencyProperty.Register(nameof(SaveCSVCommand), typeof(ICommand),
                typeof(GridRightBehavior), new PropertyMetadata(null));



        public ICommand SaveJsonCommand
        {
            get { return (ICommand)GetValue(SaveJsonCommandProperty); }
            set { SetValue(SaveJsonCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SaveJsonCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SaveJsonCommandProperty =
            DependencyProperty.Register(nameof(SaveJsonCommand), typeof(ICommand), typeof(GridRightBehavior),
                new PropertyMetadata(null));
    }


    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string ImgUrl { get; set; }
        public string ISBN { get; set; }

        public override string ToString()
        {
            return $"Id:{Id},Name:{Name},ImgUrl:{ImgUrl},ISBN:{ISBN}";
        }
    }
}

 

 

 

 

image

 

 

 

 

image

 

image

 

 

image

 

image

 

 

image

 

image

 

 

 

image

 

 

image

 

 

 

image

 

 

 

 

 

 

 

image

 

 

 

 

 

 

 

 

 

image

 

posted @ 2026-05-12 17:11  FredGrit  阅读(8)  评论(0)    收藏  举报