Thursday, February 9, 2012

WPF/C# binding XML to DataGrid

The explanation is based on a "Reminder" application I wrote using VS2010 WPF/C#.
Irrelevant lines of code along with some control attributes such as Width, Height etc are dropped in order to keep the lines shorter.

1. The structure of the XML I used:

<?xml version="1.0" encoding="utf-8" ?>
  <Reminder Title="Wash dishes" Time="3/24/2012 12:00:00" />
  <Reminder Title="Feed the fish" Time="4/24/2012 12:00:00" />
  <Reminder Title="Walk the dog" Time="5/24/2012 12:00:00" />
  <Reminder Title="Watch LOTR" Time="5/14/2012 12:00:00" />

2. The DataGrid XAML:

<DataGrid ItemsSource="{Binding Path=Elements[Reminder]}" Name="gv_reminder">
        <DataGridTextColumn Header="Title" Binding="{Binding Path=Attribute[Title].Value}"/>
        <DataGridTextColumn Header="Time" Binding="{Binding Path=Attribute[Time].Value}" />

3. The code behind:

protected void Window_Loaded(object sender, RoutedEventArgs e)
    gv_reminder.DataContext = bind_my_datagrid();

private XElement bind_my_datagrid()
    XElement bind_me = new XElement("Reminders");

            XElement data = XElement.Load(@"C:\your_path\reminder_data.xml");
    catch (Exception ex)
            throw ex;

    return bind_me;

No comments:

Post a Comment