1

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.

4

3 回答 3

2

您的绑定是错误的:您应该使用Path而不是XPath. 该XPath属性仅在绑定到 XML 数据源时使用。

<DataGridTextColumn Header="Qty" Binding="{Binding Path=Qty}" />

请注意,"Path="为简洁起见,您可以省略该部分:

<DataGridTextColumn Header="Qty" Binding="{Binding Qty}" />
于 2013-07-08T21:42:20.000 回答
1

您似乎倾向于Bind使用XPath直接Xml绑定,您只需要使用Path或仅声明该属性。

例子:

 <DataGridTextColumn Header="Qty" Binding="{Binding Qty}" />
于 2013-07-08T21:44:07.013 回答
1

而不是XPath,尝试Path给出不带 $ 的确切属性名称。

XPath用于基于 xml 的数据源。对于对象,Path使用属性绑定。

于 2013-07-08T21:42:29.330 回答