【发布时间】:2012-11-04 02:19:30
【问题描述】:
我在数据绑定和实体框架的导航属性方面遇到了一些问题。
我有两个类,由实体框架设计器生成:
Foo 类:
id (int)
bar (Bar)
...
类栏
id (int)
name (string)
...
使用ObservableCollection<Foo>,我用以下列填充了一个数据网格:
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Path=id}"/>
<DataGridTemplateColumn Header="Bar">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
SelectedValuePath="Id"
SelectedValue=
"{Binding Path=bar.Id, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="name"
ItemsSource=
"{Binding Path=BarList,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}}"
Background="White" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
ComboBox 填充了ObservableCollection<Bar>,并且正确显示了当前的Bar。
当我在组合框中选择另一个项目时,问题就出现了。我收到以下错误:
System.Windows.Data Error: 8 : Cannot save value from target back to source.
System.InvalidOperationException: The property 'Id' is part of the object's key information and cannot be modified
我知道为什么会弹出错误,但我该如何以不同的方式处理呢?
编辑:Foo 和 Bar 之间的关系是 N..1,这意味着一个 Foo 有 1 个或 0 个 Bar,而一个 Bar 可以有多个 Foos。
目前,我无法为我的Foos 选择新的Bar。
【问题讨论】:
-
你好@thakrage!你到底想在这里实现什么?更改其中一个 ViewModel 的 id 确实看起来有问题!
-
我没有使用 MVVM,但我想要一个包含 Bars 列表的组合框。从这个列表中,我希望能够为我的 Foo 选择另一个 Bar。我将编辑问题
-
即使您没有使用 MVVM,您的 DataGrid 似乎也已绑定。因此,您的每一行都是从底层对象(在您的情况下为 Foo)生成的,您想在选择 ComboBox 中的值时修改 ObservableCollection
吗?编辑:刚刚看到你的编辑:所以comboxBox是为了允许用户为给定的Foo选择一个Bar? -
完全正确。组合框旨在允许用户为每个 Foo 分配一个新 Bar。每当我这样做时,就会发生异常。
-
我会尽快为您准备好解决方案
标签: wpf data-binding datagrid combobox navigation