Skip to main content
 首页 » 编程设计

c#之涉及数据显示的极其奇怪的问题

2024年02月13日12langtianya

我有一个 DataGrid,定义如下:

 <DataGrid Name="dgResults"  
                  IsReadOnly="True" 
                  AutoGenerateColumns="True" 
                  AllowDrop="False" 
                  CanUserAddRows="False" 
                  CanUserDeleteRows="False" 
                  CanUserReorderColumns="True" 
                  CanUserResizeColumns="True" 
                  CanUserResizeRows="False" 
                  CanUserSortColumns="False" 
                  ColumnWidth="120" 
                  Margin="15,10,10,10" 
                  Visibility="Collapsed"  
                  ItemsSource="{Binding}"/> 

出于某种原因,绑定(bind)到它时没有显示任何数据。显示的行数正确,但它们都是空的。这是我的代码:

dgResults.DataContext = dtTopTwoHundredResults.AsDataView(); 
dgResults.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(dataGrid_AutoGeneratingColumn); 
dgResults.Visibility = Visibility.Visible; 
 
private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
        { 
            //Sets the DataGrid's headers to be TextBlocks, which solves a problem whereby underscore characters in the header are ignored. 
            TextBlock block = new TextBlock(); 
            block.Text = e.Column.Header.ToString(); 
            e.Column.Header = block; 
        } 

这绝对不是数据源的问题,因为数据应该包含在其中。它只是数据网格。这是它的显示方式,即正确的行数但没有数据:

我使用 Snoop 来查明文本是否实际包含在 DataGrid 中,我得到了这个:

System.Windows.Data Error: 40 : BindingExpression path error: 'Employee identification number' property not found on 'object' ''DataRowView' (HashCode=51298929)'. BindingExpression:Path=Employee identification number. Foreign key to Employee.BusinessEntityID.; DataItem='DataRowView' (HashCode=51298929); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') 
System.Windows.Data Error: 40 : BindingExpression path error: 'Employee identification number' property not found on 'object' ''DataRowView' (HashCode=51298929)'. BindingExpression:Path=Employee identification number. Foreign key to Employee.BusinessEntityID.; DataItem='DataRowView' (HashCode=51298929); target element is 'PropertyInformation' (HashCode=11239682); target property is 'Value' (type 'Object') 

请您参考如下方法:

这里的问题是列标题中涉及标点符号。删除标点符号解决了这个问题。希望有同样问题的人会读到这篇文章,因为我花了很多时间才意识到这一点。