gpt4 book ai didi

wpf - 尝试在 WPF 中设置子 DataGrid 的 itemsource 时出现 "Items collection must be empty before using ItemsSource."之类的异常

转载 作者:行者123 更新时间:2023-12-03 11:02:53 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Items collection must be empty before using ItemSource using custom list

(2 个回答)


4年前关闭。




我有一个 Datagrid 和另一个 DataGrid 嵌套在父 DataGrid 中。我需要将子 DataGrid 的 ItemSource 设置为父 DataContext 的属性。我已经尝试使用 RelativeSource 作为子 itemsource 来获取父数据上下文。

xml代码

<DataGrid Grid.Row ="1" x:Name="Grid1" ItemsSource="{Binding Path=md,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Categogy" Width="100" Binding="{Binding Path =CateName,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTemplateColumn Header="Characterictics" Width="300">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding DataContext.list, RelativeSource={RelativeSource AncestorType=DataGrid}}">
<DataGridTextColumn Binding="{Binding DataContext.list.Name, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
</DataGrid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>

View 模型
Model m = new Model();
m.CateName = "CategoryName";
m.list.Add(new Characteristics() { Name="XX", Value="00"});
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m);

Model m1 = new Model();
m1.CateName = "CategoryName1";
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m1);

list = new ObservableCollection<Characteristics>();
list.Add(new Characteristics() { Name = "XX", Value = "00" });
list.Add(new Characteristics() { Name = "XX", Value = "00" });

特性类具有名称和模型属性。

现在,我遇到了“使用 ItemsSource 之前项目集合必须为空”之类的异常。

我不确定我在哪里做错了?
有人可以帮我正确绑定(bind)子dataGrid Itemsource吗?

最佳答案

对于嵌套的 DataGrid 位置 DataGridTextColumn变成 <DataGrid.Columns>标签

<DataGrid ItemsSource="{Binding list}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>

否则 DataGridTextColumn 被解释为 Item 并导致 itemsSource 出错

并且还修复了绑定(bind),它们不需要使用父 DataContext

关于wpf - 尝试在 WPF 中设置子 DataGrid 的 itemsource 时出现 "Items collection must be empty before using ItemsSource."之类的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47689661/

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