How can I read a xml file using a class and populate it on a datagrid? The datagrid should have validation capabilities?
Xml file:
<?xml version='1.0'?>
<Data>
<Book>
<Author>John Doe</Author>
<Ti开发者_开发问答tle>Straight Track Demo</Title>
<Version>1</Version>
</Book>
</Data>
There are a couple of ways you can load up a DataGrid with XML (there are others as well):
- Using an XmlDataProvider
- Reading the XML in from the code-behind
Here's a very crude sample that uses both methods.
XAML
<Window x:Class="WpfApplication1.MyDataGrid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MyDataGrid" Height="300" Width="300">
<Window.Resources>
<XmlDataProvider x:Key="BookData"
Source="C:\Somewhere\Books.xml" XPath="Data"/>
</Window.Resources>
<StackPanel>
<DataGrid
ItemsSource="{Binding Path=Elements[Book]}"
AutoGenerateColumns="False" Height="Auto"
Name="dataGrid1"
VerticalAlignment="Top" HorizontalAlignment="Stretch">
<DataGrid.Columns>
<DataGridTextColumn
Header="Author"
Binding="{Binding Path=Element[Author].Value}"/>
<DataGridTextColumn
Header="Title"
Binding="{Binding Path=Element[Title].Value}"/>
<DataGridTextColumn
Header="Version"
Binding="{Binding Path=Element[Version].Value}" />
</DataGrid.Columns>
</DataGrid>
<DataGrid
DataContext="{StaticResource BookData}"
ItemsSource="{Binding XPath=Book}"
AutoGenerateColumns="False" Height="Auto"
Name="dataGrid2" Margin="0,25,0,0"
VerticalAlignment="Top" HorizontalAlignment="Stretch">
<DataGrid.Columns>
<DataGridTextColumn
Header="Author"
Binding="{Binding XPath=Author}"/>
<DataGridTextColumn
Header="Title"
Binding="{Binding XPath=Title}"/>
<DataGridTextColumn
Header="Version"
Binding="{Binding XPath=Version}" />
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Window>
Code Behind
using System.Windows;
using System.Xml.Linq;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MyDataGrid.xaml
/// </summary>
public partial class MyDataGrid : Window
{
public MyDataGrid()
{
InitializeComponent();
var xml = XDocument.Load( "c:\\Somewhere\\Books.xml" ).Root;
dataGrid1.DataContext = xml;
}
}
}
For Reference
Finally, here are a couple of articles:
- Binding.XPath Property on MSDN
- Customize Data Display with Data Binding and WPF > Using XML Data
- A DataGrid sample using XML data
精彩评论