Skip to main content
 首页 » 编程设计

c#之绑定(bind)数据网格后,项目集合必须为空

2024年02月05日27tuyile006

我从 SQLite 数据库填充数据网格

var mA = new System.Data.SQLite.SQLiteDataAdapter("SELECT * FROM users ORDER BY Name", DataHolder.SQLiteConnection); 
var mT = new System.Data.DataTable(); 
if (dataGrid.Columns.Count > 0) 
{ 
  return; 
} 
mA.Fill(mT); 
if (mT.Rows.Count == 0) 
{ 
  mT.Rows.Add(new object[mT.Columns.Count]); 
} 
dataGrid.ItemsSource = mT.DefaultView; 

但是在我绑定(bind) DataGrid 以更改单元格背景后,如果该代码的值等于 0

<DataGrid x:Name="dataGrid" Margin="0,10,0,0" Loaded="dataGrid_Loaded" FontSize="14"> 
   <DataGridTextColumn Binding="{Binding Active}"> 
      <DataGridTextColumn.ElementStyle> 
         <Style TargetType="{x:Type TextBlock}"> 
            <Setter Property="Background" Value="{Binding Active, Converter={StaticResource All}}"/> 
         </Style> 
      </DataGridTextColumn.ElementStyle> 
   </DataGridTextColumn> 
</DataGrid> 

IValueConverter

public class All : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
        string input = value as string;     
 
        if (System.Convert.ToByte(input) == 0) 
        { 
            return Brushes.Red; 
        } 
        else if (System.Convert.ToByte(input) > 0 && System.Convert.ToByte(input) < 5) 
        { 
            return Brushes.OrangeRed; 
        } 
        else 
        { 
            return DependencyProperty.UnsetValue; 
        } 
    } 
 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
        throw new NotSupportedException(); 
    } 
 
} 

当 DataGrid 被填充时,我在运行时遇到了那个错误

An exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll but was not handled in user code

Additional information: Items collection must be empty before using ItemsSource.

在 dataGrid.ItemsSource = mT.DefaultView;

请您参考如下方法:

您忘记在 XAML 中添加 DataGrid.Columns 标记。如果没有 DataGridTextColumn 将被视为一个项目,并且由于您设置了 ItemsSource,您会收到一个错误,提示您尝试从两个来源填充项目

<DataGrid ...> 
    <DataGrid.Columns>  
        <DataGridTextColumn>