绑定数据网格后,项集合必须为空

时间:2016-04-14 19:30:27

标签: c# wpf xaml data-binding datagrid

我从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;

但在绑定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时,我在运行时收到该错误

  

类型&#39; System.InvalidOperationException&#39;的例外情况发生在PresentationFramework.dll中但未在用户代码中处理

     

其他信息:项目集合在使用前必须为空   的ItemsSource。

dataGrid.ItemsSource = mT.DefaultView;

1 个答案:

答案 0 :(得分:4)

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

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