using System;
using System.Collections.Generic;
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.Diagnostics;
using System.IO;
namespace CustomizedWPFTaskManager
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//Load Function
OnLoad();
}
private void OnLoad()
{
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
//- Refresh process list
Process pList = new Process();
List<String> procList = new List<string>(new string[] { "" });
foreach (Process p in Process.GetProcesses())
{
try
{
FileInfo fi = new FileInfo(p.MainModule.FileName);
procList.Add(fi.Name);
TaskViewBox1.Items.Add(fi.Name);
}
catch { }
}
countLabel.Content = TaskViewBox1.Items.Count + " PROCESSES RUNNING";
}
}
}
到目前为止,这就是我所拥有的,但是我的问题是,即使这些进程已经是它们的(重复项),它们也会继续添加。我也是新手,我的老板一直在教我在商店附近提供帮助。他也希望我学习WPF。我认为这是一个很好的第一个项目,对如何删除重复项有帮助吗?同样,如果不是很多,您可以解释一下您做了些什么,但是我不仅在复制代码,而且还为下一次实际学习而做了。
最佳答案
让我们看一个使用MVVM结构模式的非常基本的示例。
首先是 View 模型。它具有Processes
属性,它是ObservableCollection<Process>
和Tick
的DispatcherTimer
事件处理程序,用于更新集合。
public class ViewModel
{
public ObservableCollection<Process> Processes { get; }
= new ObservableCollection<Process>();
public ViewModel()
{
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
timer.Tick += UpdateProcesses;
timer.Start();
}
private void UpdateProcesses(object sender, EventArgs e)
{
var currentIds = Processes.Select(p => p.Id).ToList();
foreach (var p in Process.GetProcesses())
{
if (!currentIds.Remove(p.Id)) // it's a new process id
{
Processes.Add(p);
}
}
foreach (var id in currentIds) // these do not exist any more
{
Processes.Remove(Processes.First(p => p.Id == id));
}
}
}
现在来看。这是一个简单的列表框,显示了流程集合的
Id
和ProcessName
。它的ItemsSource
绑定(bind)到 View 模型的Processes
属性。<ListBox ItemsSource="{Binding Processes}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Id}" Width="50"/>
<TextBlock Text="{Binding ProcessName}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
最后,必须将 View 模型的实例分配给MainWindow的DataContext。这可以在XAML中完成
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
或在后面的代码中
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}