如何在XML C#中序列化内置对象?

时间:2015-03-12 19:34:44

标签: c# xml wpf

我有复杂的类系统相互引用。我使用XML serialize来保存我的DataGrids。

类:

[Serializable]
public class CompJobArray
{
    [XmlElement("Room")]
    public ObservableCollection<Room> RoomList = new ObservableCollection<Room>();
    public CompJobArray() { }
}

public class Room
{
    public string roomName { get; set; }
    public double floorSquare { get; set; }
    public double ceilingSquare { get; set; }
    public double wallsSquare { get; set; }
    public double floorPerimeter { get; set; }
    public double ceilingPerimeter { get; set; }
    public ObservableCollection<CompJob> CompJobsCollection{ get; set; }

    public Room() { }

    public Room(string Name, double fS,double cS,double wS,double fP,double cP)
    {
        roomName = Name;
        floorSquare = fS;
        ceilingSquare = cS;
        wallsSquare = wS;
        floorPerimeter = fP;
        ceilingPerimeter = cP;
        CompJobsCollection = new ObservableCollection<CompJob>();
    }

}

[Serializable]
public class CompJob
{
    public job CompJobjob { get; set; }
    public float Count { get; set; }
    public float TotalPrice { get; set; }

   public CompJob() { }

    public CompJob(job tempJob, float count)
    {
        CompJobjob = tempJob;
        Count = count;
        TotalPrice = tempJob.price*count;
    }
}

[Serializable]
public class job
{

    public int id { get; set; }
    public string name { get; set; }
    public float price { get; set; }
    public string measure { get; set; }

    public job() { }

    public job(int t1, string t2, float t3, string t4)
    {
        id = t1;
        name = t2;
        price = t3;
        measure = t4;
    }
}

所有课程都在链中工作:CompJobArray-&gt; Room-&gt; CompJob-&gt; Job。

Furhter,XAML和序列化:

private void SaveMenuItem_OnClick(object sender, RoutedEventArgs e)
    {
        using (StreamWriter swr = new StreamWriter(xmlFilePath))
        {
            CompJobArray tempJobArray = new CompJobArray();
            tempJobArray.RoomList = RoomList;

            deserializerCJA.Serialize(swr, tempJobArray);
        }
    }

<DataGrid  Grid.Row="2" ItemsSource="{Binding Path=CompJobsCollection}"  CanUserAddRows="True" AutoGenerateColumns="False">
      <DataGrid.Columns>
           <DataGridTextColumn Header="Наименование элемента" Binding="{ Binding Path=CompJobjob.name, Mode=TwoWay}"  />
           <DataGridTextColumn Header="Количество" Binding="{Binding Path=Count ,Mode=TwoWay}" />
           <DataGridTextColumn Header="Сумма" Binding="{Binding Path=TotalPrice,Mode=TwoWay}" />
      </DataGrid.Columns>
</DataGrid>

最后 - 作业未保存:

<CompJobsCollection>
  <CompJob>
    <Count>12</Count>
    <TotalPrice>150</TotalPrice>
  </CompJob>
</CompJobsCollection>

详细说明:我使用类Room to ObservableCollection反序列化XML,然后我分配了Obs。收集到DataGrid。当我编辑datagrid并保存它时 - 一切都很好,除了保存在CompJob类中内置的作业类,在Room类中作为Obs内置。采集。

在我的数据网格中编辑作业字段后如何处理,保存后,我会看到xml中的更改?

0 个答案:

没有答案