数据未显示在datagrid wpf中

时间:2013-09-15 17:22:24

标签: c# wpf datagrid

我有一个数据网格来显示来自数据库的数据,数据来自两个使用外键的表。但问题是数据没有显示在网格中但行显示但行没有数据时为空。任何人都可以在我错的地方指出我的错误

        <DataGrid AutoGenerateColumns="False" Name="SParts_grid" HorizontalAlignment="Center" Margin="32,127,32,0" VerticalAlignment="Top" Height="161" Width="530" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Part Code" Width="89" Binding="{Binding Path=SPartCode, Mode=OneWay}" />
                <DataGridTextColumn Header="Part Name" Width="140" Binding="{Binding Path=SPartName, Mode=OneWay}" />
                <DataGridTextColumn Width="90"  Header="Part Price"  Binding="{Binding Path=SPartSalePrice, Mode=OneWay}" />
                <DataGridTextColumn Header="Model" Width="90" Binding="{Binding Path=ModelName, Mode=OneWay}" />
                <DataGridTextColumn Header="Location" Width="60" Binding="{Binding Path=SPartLocation, Mode=OneWay}" />
                <DataGridCheckBoxColumn Header="Active" Width="58" Binding="{Binding Path=SPartActive, Mode=OneWay}" />
            </DataGrid.Columns>
        </DataGrid>

所以我用一个类将数据库数据分配到类

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    LoadParts();
}

public class PartsListObjects
{
    public int partid;
    public string SPartName;
    public string SPartCode;
    public string SPartLocation;
    public bool SPartActive;
    public string ModelName;
    public string SPartSalePrice;
}

private void LoadParts()
{
    RST_DBDataContext conn = new RST_DBDataContext();
    List<PartsListObjects> AllParts = (from s in conn.TblSpareParts
                                       join m in conn.TblBikeModels on s.ModelID equals m.ModelID
                                       select new PartsListObjects() { SPartName = s.SPartName, SPartCode = s.SPartCode, SPartLocation = s.SPartLocation, SPartSalePrice = s.SPartSalePrice.ToString(), ModelName = m.ModelName, SPartActive = s.SPartActive }).ToList();

    SParts_grid.ItemsSource = AllParts;

    SParts_grid.Items.Refresh();
}

2 个答案:

答案 0 :(得分:3)

你应该绑定属性,而不是字段。

将您的模型类更改为以下代码:

public class PartsListObjects
{
    public int partid {get; set; }
    public string SPartName {get; set; }
    public string SPartCode {get; set; }
    public string SPartLocation {get; set; }
    public bool SPartActive {get; set; }
    public string ModelName {get; set; }
    public string SPartSalePrice {get; set; }
}

答案 1 :(得分:0)

在Datagrid属性的xaml代码中将属性CanUserReorderColumns="false"设置为true