lundi 9 avril 2012

XmlDataProvider GroupBy an item in a DataGrid (two way binding)

This post will be done in english.

I'm not reinventing the wheel but I just had to implement this a simple datagrid grouped by a certain type of value. The datasource of the datagrid come from an XmlDataProvider.

Here is the xml file sample:


<?xml version="1.0" encoding="utf-8" ?>
<ListeDePrix>
  <Articles nom="Telephone" value="15"  vente="500" location="60,00" />
  <Articles nom="Telephone" value="50"  vente="450" location="45,50" />
  <Articles nom="Telephone" value="250" vente="300" location="35,50" />
  
  <Articles nom="Television" value="15"  vente="600" location="55" />
  <Articles nom="Television" value="50"  vente="500" location="50" />
  <Articles nom="Television" value="250" vente="400" location="30" />
  
  <Articles nom="Tablet" value="15"  vente="475" location="40" />
  <Articles nom="Tablet" value="50"  vente="425" location="37"  />
  <Articles nom="Tablet" value="250" vente="375" location="32"  />
</ListeDePrix>

Here is the XAML file:

<Window.Resources>
        <XmlDataProvider x:Key="xmlfile" Source="XMLtest.xml" XPath="ListeDePrix/Articles"/>
    </Window.Resources>
    <StackPanel>
        <DataGrid AutoGenerateColumns="False">
            <DataGrid.Resources>
                <CollectionViewSource x:Key="items" Source="{Binding Source={StaticResource xmlfile}}">
                    <CollectionViewSource.GroupDescriptions>
                        <PropertyGroupDescription PropertyName="@value" />
                    </CollectionViewSource.GroupDescriptions>
                </CollectionViewSource>
            </DataGrid.Resources>
            <DataGrid.ItemsSource>
                <Binding Source="{StaticResource items}"/>
            </DataGrid.ItemsSource>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding XPath=@nom, Mode=TwoWay}" Header="nom"/>
                <DataGridTextColumn Binding="{Binding XPath=@value, Mode=TwoWay}" Header="value"/>
                <DataGridTextColumn Binding="{Binding XPath=@location, Mode=TwoWay}" Header="Renting price"/>
                <DataGridTextColumn Binding="{Binding XPath=@vente, Mode=TwoWay}" Header="Sell price"/>
            </DataGrid.Columns>
            <DataGrid.GroupStyle>
                <GroupStyle />
            </DataGrid.GroupStyle>
        </DataGrid>
        <Button Content="Save" Height="23" Name="button1" Width="75" HorizontalAlignment="Left" Click="button1_Click" />
    </StackPanel>

I've added some code behind in order to be able to save the data into the xml file.



Code:
 private void button1_Click(object sender, RoutedEventArgs e)
        {
            XmlDataProvider xmlfile = (XmlDataProvider)FindResource("xmlfile");

            string source = xmlfile.Source.LocalPath;
            xmlfile.Document.Save(source);
        }

Aucun commentaire:

Publier un commentaire