【问题标题】:Bind DataGrid to List<T>, but only show selection of T's properties将 DataGrid 绑定到 List<T>,但只显示 T 的属性选择
【发布时间】:2013-07-08 21:38:19
【问题描述】:

所以,有一个自定义类,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";
    }
}

我有一个listMaterial

var myList = new List<Material>
                 {
                     new Material()
                 };

它被设置为我的DataGrid的项目来源:

dataGrid1.ItemsSource = myList;

现在,在 XAML 中,如果我设置 AutoGenerateColumns="True",它会根据 Material 的属性为 dataGrid1 创建标头。但是,我只想要 4 列,QtyDescriptionSupplierPONumber。所以,我写了以下内容:

 <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>

我的问题是,现在dataGrid1 是空的。我觉得我错过了一些完全愚蠢的东西,我希望一双新的眼睛能帮助我发现这一点。

所以,我的问题是,我是不是走错了路?有没有办法将List&lt;Material&gt; 绑定到dataGrid1 并且只显示我想要的列?

我尝试的网站是herehere

【问题讨论】:

    标签: c# wpf binding datagrid


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

      代替XPath,尝试Path 并给出不带$ 的确切属性名称。

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

      【讨论】:

        【解决方案3】:

        您似乎将Bind 转换为用于直接Xml 绑定的XPath,您只需使用Path 或仅声明属性。

        例子:

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

        【讨论】:

          猜你喜欢
          • 2014-05-12
          • 1970-01-01
          • 2012-12-11
          • 1970-01-01
          • 1970-01-01
          • 2017-02-08
          • 2010-09-12
          • 1970-01-01
          • 2011-05-09
          相关资源
          最近更新 更多