我曾尝试将xml文件读取/保存到datagrid,我正在使用数据集来执行此操作。现在我已成功将xml文件数据加载到datagrid,代码如下:
public class StoreDb
{
public ObservableCollection<Product> GetProducts()
{
DataSet ds = StoreDbDataSet.ReadDataSet();
ObservableCollection<Product> products = new ObservableCollection<Product>();
foreach (DataRow productRow in ds.Tables["Products"].Rows)
{
products.Add(new Product((string)productRow["ModelNumber"],
(string)productRow["ModelName"], (string)productRow["InputAddress"],
(string)productRow["OutputAddress"], (string)productRow["DiagAddress"],
(string)productRow["Description"], (byte)productRow["CategoryID"],
(string)productRow["CategoryName"], (string)productRow["ProductImage"]));
}
return products;
}
}
和
<DataGrid Name="dgBasicInfo" ItemsSource="{Binding ProductsView, Mode=TwoWay}" CanUserResizeColumns="False" AutoGenerateColumns="False" Margin="10,10,10,15" BorderThickness="5" FontSize="14" Background="White">
<DataGrid.Columns>
<DataGridTextColumn Header="SlaveId" Binding="{Binding CategoryID}" />
<DataGridTextColumn Header="ModelName" Binding="{Binding ModelName}"/>
<DataGridTextColumn Header="CategoryName" Binding="{Binding CategoryName}" />
<DataGridTextColumn Header="InputAddress" Binding="{Binding InputAddress}" />
<DataGridTextColumn Header="OutputAddress" Binding="{Binding OutputAddress}" />
<DataGridTextColumn Header="DiagAddress" Binding="{Binding DiagAddress}" />
<DataGridTextColumn Header="Specification" Binding="{Binding Description}" />
</DataGrid.Columns>
</DataGrid>
Xaml文件:
public ICollectionView ProductsView
{
get { return _ProductsView; }
set
{
_ProductsView = value;
NotifyPropertyChanged();
}
}
ViewModel:
private void RefreshProductList()
{
ProductsView = new ListCollectionView(sdb.GetProducts())
{
Filter = obj =>
{
var Product = (Product)obj;
return SelectedProduct != null && Product.ModelNumber == SelectedProduct.ModelNumber;
}
};
}
private Product selectedProduct;
public Product SelectedProduct
{
get { return selectedProduct; }
set
{
if (selectedProduct != value)
{
selectedProduct = value;
NotifyPropertyChanged();
RefreshProductList();
RefreshModule();
RefreshCommunication();
List<Product> productlist = ProductsView.ToList();
File.WriteAllText("store.xml", productlist.ToXML());
}
}
}
我的问题是当我更改datagrid数据时,如何将更改保存到xml?提前感谢!
---------------------------更新------------------- ------------
{{1}}
答案 0 :(得分:1)
问题是您正在将xml作为数据集读取而是将其作为产品读取并将其另存为产品数组,如下所示
您的xml格式应如下所示
<ArrayOfProduct>
<Product>
<ModelNumber>abc</ModelNumber>
//remaking properties
</Product>
</ArrayOfProduct>
创建一个扩展方法类,这有助于您将xml转换为列表反之亦然
public static class ExtensionMethods
{
/// <summary>
/// Converts given class to XML using xml serialization
/// </summary>
/// <typeparam name="T">Type of Class</typeparam>
/// <param name="classObject">Class to be serialized</param>
/// <returns>Xml string</returns>
public static string ToXML<T>(this T classObject) where T : class
{
XmlSerializer xmls = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineChars = Environment.NewLine;
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Document;
using (XmlWriter writer = XmlTextWriter.Create(ms, settings))
{
xmls.Serialize(writer, classObject);
}
string xml = Encoding.UTF8.GetString(ms.ToArray());
return xml;
}
}
/// <summary>
/// Converts given XML string to class of type T
/// </summary>
/// <typeparam name="T">Type to be converted</typeparam>
/// <param name="XmlData">xml string</param>
/// <returns>class of Type T</returns>
public static T ToClass<T>(this string XmlData)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
T newClass;
using (XmlTextReader reader = new XmlTextReader(new StringReader(XmlData)))
{
//reader.Namespaces = false;
newClass = (T)serializer.Deserialize(reader);
}
return newClass;
}
}
现在你的商店db应该是这样的
public class StoreDb
{
public ObservableCollection<Product> GetProducts()
{
string StoreData = string.Empty;
using(StreamReader sr = new StreamReader("store.xml"))
{
StoreData = sr.ReadToEnd();
}
ObservableCollection<Product> products = new ObservableCollection<Product>(StoreData.ToClass<List<Product>());
return products;
}
}
将productsView更改为observablecollection
private ObservableCollection<Product> _ProductsView;
public ObservableCollection<Product> ProductsView
{
get { return _ProductsView; }
set
{
_ProductsView = value;
NotifyPropertyChanged();
}
}
现在更改后保存xml如下
File.WriteAllText("store.xml",ProductsView.ToList().ToXml());