wpf 为什么在构造函数中更新到当前日期时间后,日期时间更改为0001-01-01 00:00:00?[已关闭]

3b6akqbq  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(126)

已关闭,此问题需要details or clarity。它目前不接受回答。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

关闭7天前。
Improve this question
mainwindow.xaml.cs代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace wpfMultiThreadListViewUpdate
{
    public class ProcessesInfo
    {
        public string Name { get; set; }
        public string Status { get; set; }
        public int Id { get; set; }
        public long MemoryUsage { get; set; }
        public List<ProcessesInfo> SubProcesses { get; set; } = new List<ProcessesInfo>();
        public DateTime ProcessDateTime { get; set; }
    }

    public partial class MainWindow : Window
    {
        private Dictionary<int, ProcessesInfo> processDictionary = new Dictionary<int, ProcessesInfo>();
        Process[] processes;

        // New property for selected process
        public ProcessesInfo SelectedProcess { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public MainWindow()
        {
            InitializeComponent();

            WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            processes = Process.GetProcesses();

            showInformation(processes.Length, lstvw);

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += Timer_Elapsed;
            timer.Interval = new TimeSpan(0, 0, 1).TotalMilliseconds;
            timer.Start();
        }

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

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            UpdateProcessList();
        }

        private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            
        }

        private void UpdateProcessList()
        {
            // New list to hold the updated process information
            List<ProcessesInfo> updatedProcessList = new List<ProcessesInfo>();

            processes = Process.GetProcesses();

            // Check for killed processes and update the status
            foreach (var processInfo in processDictionary.Values.ToList())
            {
                ProcessesInfo updatedProcess = new ProcessesInfo
                {
                    Name = processInfo.Name,
                    Id = processInfo.Id,
                    MemoryUsage = processInfo.MemoryUsage,
                    SubProcesses = processInfo.SubProcesses
                };

                if (processes.All(p => p.Id != processInfo.Id))
                {
                    updatedProcess.Status = "Killed";
                }
                else
                {
                    updatedProcess.Status = "Opened";
                }

                updatedProcessList.Add(updatedProcess);
            }

            // Check for new processes and add them to the dictionary
            foreach (var process in processes)
            {
                if (!processDictionary.ContainsKey(process.Id))
                {
                    processDictionary.Add(process.Id, new ProcessesInfo
                    {
                        Name = process.ProcessName,
                        Id = process.Id,
                        Status = "Opened",
                        MemoryUsage = process.WorkingSet64 / 1024,
                    });

                    updatedProcessList.Add(processDictionary[process.Id]);
                }
                else
                {
                    // Update memory usage for existing processes
                    processDictionary[process.Id].MemoryUsage = process.WorkingSet64 / 1024;
                    updatedProcessList.Add(processDictionary[process.Id]);

                    // Check if the process status has changed
                    if (processDictionary[process.Id].Status != "Killed" && processDictionary[process.Id].Status != "Opened")
                    {
                        processDictionary[process.Id].Status = "Opened";
                    }
                }
            }

            // Update the ListView with the latest process information
            Dispatcher.BeginInvoke(new Action(delegate ()
            {
                // Replace the entire data source with the updated list
                lstvw.ItemsSource = updatedProcessList;

                // Set the selected item to the previous selection if it still exists
                if (SelectedProcess != null && updatedProcessList.IndexOf(SelectedProcess) >= 0)
                {
                    lstvw.SelectedItem = SelectedProcess;
                }
            }));
        }

        private void showInformation(int numberToGet, ListView listvw)
        {
            List<ProcessesInfo> information = getInfo(numberToGet);
            Dispatcher.BeginInvoke(new Action(delegate ()
            {
                foreach (var processInfo in information)
                {
                    // Set the ProcessDateTime property for each process
                    processInfo.ProcessDateTime = DateTime.Now;
                }

                lstvw.ItemsSource = information;
            }));
        }

        private List<ProcessesInfo> getInfo(int numberToGet)
        {
            List<ProcessesInfo> info = new List<ProcessesInfo>();

            for (int i = 0; i < numberToGet; i++)
            {
                info.Add(new ProcessesInfo()
                {
                    Name = processes[i].ProcessName,
                    Status = "Opened",
                    Id = processes[i].Id,
                    ProcessDateTime = DateTime.Now // Initialize ProcessDateTime here
                });
            }

            return info;
        }

        private void expandButton_Click(object sender, RoutedEventArgs e)
        {
            // Handle sub-process expand button click here
            ToggleButton button = (ToggleButton)sender;
            ListViewItem listViewItem = FindVisualParent<ListViewItem>(button);
            ProcessesInfo selectedProcess = (ProcessesInfo)listViewItem.DataContext;

            if (button.IsChecked == true)
            {
                // Sub-processes are expanded
                foreach (var subProcess in selectedProcess.SubProcesses)
                {
                    processDictionary.Add(subProcess.Id, subProcess);
                }
            }
            else
            {
                // Sub-processes are collapsed
                foreach (var subProcess in selectedProcess.SubProcesses)
                {
                    processDictionary.Remove(subProcess.Id);
                }
            }

            UpdateProcessList();
        }

        private static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                if (parent is T correctlyTyped)
                {
                    return correctlyTyped;
                }
                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }
    }
}

当第一次运行应用程序时,所有进程在一秒钟内显示日期时间列中的当前日期时间,但在一秒钟后,所有进程的所有日期时间显示0001-01-01 00:00:00
为什么要更改为0001-01-01 00:00:00,以及如何修复它,使其保持当前的日期时间?

toe95027

toe950271#

创建新ProcessesInfo对象时忘记复制属性。

// Check for killed processes and update the status
foreach (var processInfo in processDictionary.Values.ToList())
{
    ProcessesInfo updatedProcess = new ProcessesInfo
    {
        Name = processInfo.Name,
        Id = processInfo.Id,

        // --------------------------
        // This is missing
        // --------------------------
        ProcessDateTime = processInfo.ProcessDateTime, 

        MemoryUsage = processInfo.MemoryUsage,
        SubProcesses = processInfo.SubProcesses,
    };

    if (processes.All(p => p.Id != processInfo.Id))
    {
        updatedProcess.Status = "Killed";
    }
    else
    {
        updatedProcess.Status = "Opened";
    }

    updatedProcessList.Add(updatedProcess);
}

相关问题