如何从datagrid获取数据并写入wpf中的xml文件 [英] How to get data from datagrid and write into xml file in wpf

查看:64
本文介绍了如何从datagrid获取数据并写入wpf中的xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些中介,所以我想创建xml文件作为临时存储。所以需要从按钮点击数据网格中获取数据并写入xml文件然后再次形成加载然后从xml文件读取并将数据传递给datagrid

Me need some mediator so i like to create xml file as temp storage.so need get the data from datagrid on button click and write into xml file and then again form load then read from xml file and pass data to datagrid

推荐答案

你的Wpf中的DataGrid是否包含强力输入的数据???



例如,我的意思是像IList< person>这样的东西或者ICollection< person>,其中你的域模型代表单行数据。

如果是,所以在这种情况下你需要访问WPF中的ItemsSource属性。



我假设您根据前一个问题编写此问题=)

因此在执行从DataGrid到临时xml文件的批量复制操作的情况下,有没有这样的需要使用Mediator技术...



因此,假设您有DataGrid名为dg1:

< datagrid x:name =dg1... =xmlns:x =#unknown/>



在你的按钮处理程序中写下:

Hi , Does your DataGrid in Wpf contains stongly typed data ???

For example, I mean something like IList<person> or ICollection<person>, where person your domain model which represent single row data.
If yes, so in such case all you need to access to ItemsSource property in WPF.

I assume that you write this question based on your previous one =)
So in such case for performing operation of bulk copy from DataGrid to temporary xml file, there is no such need to use Mediator technic...

So,as a result, lets assume that you have DataGrid called dg1:
<datagrid x:name="dg1" ...="" xmlns:x="#unknown" />

In your button handler write next:
private void ...Click(...)
{
 var items=dg1.ItemsSource;
  if(items!=null)
  {
    foreach(var entity in items)
    {
      var entType=entity.GetType();
      //there you can get all properties and data from method below
    }
  }
}







var SomeObject = new { .../*properties*/... };
var PropertyInfos = SomeObject.GetType().GetProperties();
foreach(PropertyInfo pInfo in PropertyInfos)
{
    string propertyName = pInfo.Name; //gets the name of the property
    doSomething(pInfo.GetValue(SomeObject,null));
}







或者您可以使用更简单的方法来使用XmlSerializer :






Or you can use more simple way to do it by usage of XmlSerializer:

....
{
//all stuff must be performed in buton click handler
XmlSerializer serialiser = new XmlSerializer(dg1.ItemsSource.GetType());
// Create the TextWriter for the serialiser to use
TextWriter Filestream = new StreamWriter(@"C:\output.xml");
//write to the file
serialiser.Serialize(Filestream , );
// Close the file
WriteFileStream.Close();
}





希望这可以提供帮助。



Hope this can help.


这篇关于如何从datagrid获取数据并写入wpf中的xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆