gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:12:39 25 4
gpt4 key购买 nike

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

关于c# - 绑定(bind)数据网格后,项目集合必须为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36632290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com