用wpf写一个表格,第一列表示时间,第二列表示报警信息,并且数据源可以动态添加,数量达到一定值本地储存
时间: 2024-05-15 13:16:31 浏览: 136
实现这个功能,首先需要在WPF中创建一个DataGrid控件,并设置两列,分别为时间和报警信息。然后,需要创建一个类来表示报警信息,包含时间和报警内容两个属性。
接着,需要将报警信息添加到数据源中。可以使用ObservableCollection来保存报警信息,这样当有新的报警信息添加时,DataGrid会自动更新显示。同时,为了达到本地存储的目的,可以将ObservableCollection序列化为XML,并保存到本地文件中。
下面是一个简单的示例代码:
MainWindow.xaml:
```
<Window x:Class="WpfApp1.MainWindow"
...
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Binding="{Binding Time}" />
<DataGridTextColumn Header="Alarm" Binding="{Binding Alarm}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
```
MainWindow.xaml.cs:
```
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Serialization;
using System.Windows;
using System.Windows.Threading;
namespace WpfApp1
{
public partial class MainWindow : Window
{
private ObservableCollection<Alarm> alarms;
public MainWindow()
{
InitializeComponent();
// Load alarms from file
alarms = LoadAlarms();
// Set data source for the DataGrid
dataGrid.ItemsSource = alarms;
// Start timer to add new alarms
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
// Add a new alarm to the collection
alarms.Add(new Alarm() { Time = DateTime.Now, Alarm = "New alarm" });
// Save alarms to file
SaveAlarms(alarms);
}
private void SaveAlarms(ObservableCollection<Alarm> alarms)
{
// Serialize alarms to XML and save to file
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Alarm>));
using (StreamWriter writer = new StreamWriter("alarms.xml"))
{
serializer.Serialize(writer, alarms);
}
}
private ObservableCollection<Alarm> LoadAlarms()
{
// Load alarms from file
if (File.Exists("alarms.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Alarm>));
using (StreamReader reader = new StreamReader("alarms.xml"))
{
return (ObservableCollection<Alarm>)serializer.Deserialize(reader);
}
}
else
{
return new ObservableCollection<Alarm>();
}
}
}
public class Alarm
{
public DateTime Time { get; set; }
public string Alarm { get; set; }
}
}
```
阅读全文