【发布时间】: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