Reputation: 6918
So, there's a custom class, Material
:
class Material
{
public string Qty { get; set; }
public string Description { get; set; }
public string Supplier { get; set; }
public string PONumber { get; set; }
public string RigName { get; set; }
public string ProjectName { get; set; }
public string ShipTo { get; set; }
public string ShipVia { get; set; }
public Material()
{
Qty = "5";
Description = "This is a test";
Supplier = "Wal-Mart";
PONumber = "23423";
RigName = "Test Rig";
ProjectName = "Test Project";
ShipTo = "Kevin";
ShipVia = "Danny";
}
}
I have a list
of Material
:
var myList = new List<Material>
{
new Material()
};
And it's set as the item source for my DataGrid
:
dataGrid1.ItemsSource = myList;
Now, in the XAML, if I set the AutoGenerateColumns="True"
, it creates the headers for dataGrid1
based upon the properties of Material
. However, I only want 4 columns, Qty
, Description
, Supplier
, and PONumber
. So, I wrote the following:
<DataGrid AutoGenerateColumns="False"
Name="dataGrid1">
<DataGrid.Columns>
<DataGridTextColumn Header="Qty"
Binding="{Binding XPath=@Qty}" />
<DataGridTextColumn Header="Description"
Binding="{Binding XPath=@Description}" />
<DataGridTextColumn Header="Supplier"
Binding="{Binding XPath=@Supplier}" />
<DataGridTextColumn Header="PO#"
Binding="{Binding XPath=@PONumber}" />
</DataGrid.Columns>
</DataGrid>
My problem is that now, dataGrid1
is empty. I have the feeling I'm missing something completely silly, and I'm hoping a fresh pair of eyes can help me spot this.
So, my question is, am I going about this the wrong way? Is there a way to bind the List<Material>
to dataGrid1
and only show the columns that I want?
The websites I based my attempts on are here and here.
Upvotes: 1
Views: 259
Reputation: 43616
You seem to be tring to Bind
to an XPath
which is used for direct Xml
bindings, You only need to use Path
or just declare the property.
Example:
<DataGridTextColumn Header="Qty" Binding="{Binding Qty}" />
Upvotes: 1
Reputation: 30718
Instead of XPath
, try Path
and give exact proprty name without $.
XPath
is used for xml based data source. For objects, Path
property binding is used.
Upvotes: 1
Reputation: 292565
Your bindings are wrong: you should use Path
instead of XPath
. The XPath
property is only used when binding to an XML data source.
<DataGridTextColumn Header="Qty" Binding="{Binding Path=Qty}" />
Note that you can omit the "Path="
part for brevity:
<DataGridTextColumn Header="Qty" Binding="{Binding Qty}" />
Upvotes: 2