0

Im trying to bind some XML data to a DataGrid, the code is working fine, but i can't bind to attribute values.

<DataGrid Name="productGrid"  HorizontalAlignment="Left" Margin="10,66,0,0" VerticalAlignment="Top" Height="459" Width="748" AutoGenerateColumns="false">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding Path=Element[product].Attribute[id].Value}" />
            <DataGridTextColumn Header="Kategori" Binding="{Binding Path=Element[category].Value}" />
            <DataGridTextColumn Header="Title" Binding="{Binding Path=Element[title].Value}" />
            <DataGridTextColumn Header="Beskrivelse" Binding="{Binding Path=Element[description].Value}" />
            <DataGridTextColumn Header="Pris" Binding="{Binding Path=Element[price].Value}" />
        </DataGrid.Columns>
    </DataGrid>

Code behind:

        public Page1()
    {
        InitializeComponent();

        var xElem = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + @"\\Data\\Products.xml");

        this.defaultView = CollectionViewSource.GetDefaultView(xElem.Elements("product"));
        this.defaultView.Filter = w => ((XElement)w).ToString().Contains(freeText.Text);

        productGrid.ItemsSource = this.defaultView;

    }

    private void SearchProducts(object sender, RoutedEventArgs e)
    {
        // Filter GridView
        this.defaultView.Refresh();
    }

Is it possible to bind a column to an attribute value? if so, how?

And is there a more elegant way of binding the columns, maybe from the code behind?

user1359448
  • 1,539
  • 3
  • 14
  • 23
  • Show your XML structure.. and believe me binding from code-behind won't be any prettier – har07 Jun 18 '14 at 02:35

1 Answers1

0

You can remove some of the extra element from the binding i.e. Element[product] in this case, these are not required as the bound element is product itself

eg

<DataGrid Name="productGrid"  HorizontalAlignment="Left" Margin="10,66,0,0" VerticalAlignment="Top" Height="459" Width="748" AutoGenerateColumns="false">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding Path=Attribute[id].Value}" />
        <DataGridTextColumn Header="Kategori" Binding="{Binding Path=Element[category].Value}" />
        <DataGridTextColumn Header="Title" Binding="{Binding Path=Element[title].Value}" />
        <DataGridTextColumn Header="Beskrivelse" Binding="{Binding Path=Element[description].Value}" />
        <DataGridTextColumn Header="Pris" Binding="{Binding Path=Element[price].Value}" />
    </DataGrid.Columns>
</DataGrid>
pushpraj
  • 13,458
  • 3
  • 33
  • 50