我試圖讀取/保存xml文件到datagrid,我使用數據集來做到這一點。現在,我已經成功將XML文件中的數據加載到數據網格,代碼如下:WPF將數據集保存到xml
public class StoreDbDataSet
{
internal static DataSet ReadDataSet()
{
DataSet ds = new DataSet();
ds.ReadXmlSchema("store.xsd");
ds.ReadXml("store.xml");
return ds;
}
}
和:
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;
}
}
XAML文件:
<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>
視圖模型:
public ICollectionView ProductsView
{
get { return _ProductsView; }
set
{
_ProductsView = value;
NotifyPropertyChanged();
}
}
我的問題是當我改變了數據網格數據,我怎樣才能保存更改爲XML?提前致謝!
--------------------------- update ------------------ -------------
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());
}
}
}
如何[中WriteXML ](https://msdn.microsoft.com/en-us/library/system.data.datase t.writexml(V = vs.110)的.aspx)? – CodingYoshi
我這樣做了,但它只是創建一個新的空XML文件。 –
你寫給xml的哪個組件? 您將您的數據綁定到ProductsView, 請參閱setter方法的更改。如果發生更改,則將其寫入XML。 –