【问题标题】:Items collection must be empty after binding the datagrid绑定数据网格后,项目集合必须为空
【发布时间】:2016-04-14 19:30:27
【问题描述】:

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

IValue 转换器

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 被填充时,我在运行时收到该错误

PresentationFramework.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理

附加信息:Items 集合在使用前必须为空 项目来源。

dataGrid.ItemsSource = mT.DefaultView;

【问题讨论】:

  • 当控件也包含硬编码元素时会发生此错误。比如在组合框中添加一些comboboxitem,然后也设置itemssource,你会得到这个错误。

标签: c# wpf xaml data-binding datagrid


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2016-03-23
    • 1970-01-01
    • 2012-07-24
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多