【发布时间】:2017-11-21 18:34:32
【问题描述】:
我在 ListView 中输入了一些值。我在 MainWindow() 方法中执行此操作,然后再执行此操作。虽然后面添加的数据可以改,但是我在MainWindow()方法里放的值是不能改的 我工作的主窗口类从 xml 文件加载数据并输入到 ObservationCollection
ObservableCollection<MonitorData> monitorList = new ObservableCollection<MonitorData>();
public ObservableCollection<MonitorData> MonitorList
{
get
{
return monitorList;
}
}
public MainWindow()
{
DataContext = this;
InitializeComponent();
using (XmlReader reader = XmlReader.Create(@"/monitor.xml"))
{
string name = string.Empty;
string address = string.Empty;
string type = string.Empty;
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name.ToString())
{
case "name":
name = reader.ReadElementContentAsString();
break;
case "address":
address = reader.ReadElementContentAsString();
break;
case "type":
type = reader.ReadElementContentAsString();
monitorList.Add(new MonitorData() { Name = name, Address = address, Type = type });
break;
}
}
}
}
xaml - 我尝试从 xml 文件中呈现数据
<Window
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:Monitor" x:Class="Monitor.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="1332.047" Width="810">
<Window.Resources>
<Style TargetType="{x:Type GridViewColumnHeader}">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</Window.Resources>
<Grid>
<ListView Margin="5" x:Name="MonitoringListView" ItemsSource="{Binding MonitorList}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="200" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Address" Width="200" DisplayMemberBinding="{Binding Address}"/>
<GridViewColumn Header="Type" Width="200" DisplayMemberBinding="{Binding Type}"/>
<GridViewColumn Header="Availability" Width="200" DisplayMemberBinding="{Binding Enabled}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
我的班级
public class MonitorData
{
public string Name { get; set; }
public string Address { get; set; }
public string Type { get; set; }
public bool Enabled { get; set; }
}
我每 10 秒添加一次数据并尝试更改它, 可以更改我在 Timer_Tick 中添加的数据,但不知何故无法从 xml 文件更改我在 MainWindow() 中输入的数据
private void Timer_Tick(object sender, EventArgs e)
{
monitorList.Add(new MonitorData() { Name = "new", Address = "111", Type = "sometype", Enabled = true });
for (int i = 0; i < monitorList.Count; i++)
{
monitorList[i].Name = "new name";
monitorList[i].Enabled = true;
}
}
【问题讨论】: