如何使用MVVM将DataGridComboBoxColumn绑定到EntityFramework? [英] How do I bind a DataGridComboBoxColumn to EntityFramework using MVVM?
问题描述
我正在尝试使DataGridComboBoxColumn与ViewModel一起使用.一切似乎都能正常工作,但是当我更改组合框的值时,实体没有更改.
I'm trying to get a DataGridComboBoxColumn working with my ViewModel. Everything appears to work correctly but when I change the value of the combo box, the entity isn't changed.
窗口的数据上下文具有以下属性:
The datacontext of the window has these properties:
ItemsSource
Public Property AllEnergySources() As ObservableCollection(Of EnergySourceViewModel)
SelectedItemBinding
Private _CurrentEnergySource As EnergySourceViewModel
Public Property CurrentEnergySource() As EnergySourceViewModel
Get
Return _CurrentEnergySource
End Get
Set(ByVal value As EnergySourceViewModel)
_CurrentEnergySource = value
OnPropertyChanged("CurrentEnergySource")
End Set
End Property
我觉得问题出在我如何在作为DataContext的ViewModel中填充CurrentEnergySource:
I feel the problem lies with how I populate CurrentEnergySource in the ViewModel that is the DataContext:
Sub New(SelectedEntity as EquipmentEnergySource)
AllEnergySources = New ObservableCollection(Of EnergySourceViewModel)
//Select all EnergySources from the EntityFramework
Dim EnergyEntities = From esr in db.EnergySources Select esr
//Loop through to convert Entity POCO to Collection of ViewModels
For Each es In EnergyEntities
_AllEnergySources.Add(New EnergySourceViewModel(es))
//Optionally Set the newly created ViewModel to SelectedItemBinding object
If es.EnergySourceID = SelectedEntity.EnergySourceID Then
_CurrentEnergySource = _AllEnergySources.Last
End If
Next
End Sub
当我为组合框创建后备集合时,如果模型是所选模型,则将那个视图模型设置为CurrentEnergySource,但是在那之后它就被断开了(这就是问题所在)
When I create the backing collection for the combobox, if the model is the selected one, I set that viewmodel to be the CurrentEnergySource but after that point it is disconnected(and that's the problem)
我应该在CurrentEnergySource中引用什么,以便在组合框更改时更新模型?
What should I reference in CurrentEnergySource so that it updates the model when the combo box changes?
推荐答案
我的答案是您需要手动更改外键(我现在在CurrentEnergySource的设置器中对其进行更改,这是SelectedItemBinding绑定的属性)
My answer is you need to change the foreign key manually (I now change it in the setter of CurrentEnergySource, which is the SelectedItemBinding bound property)
Private _CurrentEnergySource As EnergySourceViewModel
Public Property CurrentEnergySource() As EnergySourceViewModel
Get
Return _CurrentEnergySource
End Get
Set(ByVal value As EnergySourceViewModel)
_CurrentEnergySource = value
Me.Model.EnergySourceID = value.Model.EnergySourceID
OnPropertyChanged("CurrentEnergySource")
End Set
End Property
在加载时,填充私有后备存储_CurrentEnergySource
而不是属性,以避免所有对象以修改后的状态开始
On load, populate the private backing store _CurrentEnergySource
instead of the property to avoid all objects starting out with modified state
这篇关于如何使用MVVM将DataGridComboBoxColumn绑定到EntityFramework?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!