目标
使用模型、 View 、 View 模型 (MVVM) 的方式将自定义类对象 (DamagedItems) 的列表添加到 DataGrid。
我希望用户能够创建损坏部件的条目(在检查机器时被认为不正确)。
我做了什么
我创造了:
DataContext
设置为 DamagedItemViewModel
INotifyPropertyChanged
DamagedItemModel
ObservableCollection(Of DamagedItemModel)
由于我的 DataContext 设置为 损坏项目查看模型 ,这是我设置属性的方式:
Public Class DamagedItemViewModel
Private _DamagedItem As DamagedItemModel
Private _Add As ICommand
Private _DamagedItems As DamagedItemList
Public Property DamagedItem As DamagedItemModel
Get
Return _DamagedItem
End Get
Set(value As DamagedItemModel)
_DamagedItem = value
End Set
End Property
Public Property DamagedItems As DamagedItemList
Get
Return _DamagedItems
End Get
Set(value As DamagedItemList)
_DamagedItems = value
End Set
End Property
Public Property Add As ICommand
Get
Return _Add
End Get
Set(value As ICommand)
_Add = value
End Set
End Property
Public Sub New()
DamagedItem = New DamagedItemModel("", "", "")
DamagedItems = New DamagedItemList
Add = New DamagedItemAddEntryCommand(Me)
End Sub
Public Function CanUpdate() As Boolean
If DamagedItem.Description = "" Then Return False
If DamagedItem.Initiales = "" Then Return False
Return True
End Function
Public Sub AddEntry()
DamagedItems.Add(DamagedItem) 'Items get added to the datagrid
DamagedItem = New DamagedItemModel 'Does not seem to clear textboxes
End Sub
End Class
这是我的 XAML 的设置方式:
<DataGrid ItemsSource="{Binding Path=DamagedItems}" AutoGenerateColumns="True" HorizontalAlignment="Stretch" Margin="12,90,12,0" Name="DataGrid1" VerticalAlignment="Top" Height="229" / >
<TextBox Text="{Binding DamagedItem.Description, UpdateSourceTrigger=PropertyChanged}" Height="23" HorizontalAlignment="Left" Margin="88,24,0,0" VerticalAlignment="Top" Width="249" />
<TextBox Text="{Binding DamagedItem.Initiales, UpdateSourceTrigger=PropertyChanged}" Height="23" HorizontalAlignment="Left" Margin="88,58,0,0" VerticalAlignment="Top" Width="249" />
如您所见,我的文本框绑定(bind)到我的模型(它包含在我的 ViewModel 中,它绑定(bind)到该窗口的 DataContext)。每当我单击“添加”按钮时,文本框中的任何内容都会添加到 DataGrid,但文本框中的内容仍保留在那里。
这一步很好,我写上我要添加的内容然后点击“添加”
单击“添加”后,我在 DataGrid 中得到以下结果,这很好。问题是我的文本框仍然充满了数据,但模型已被清除(参见 DamagedItemViewModel
AddEntry
方法之后的代码)。现在,当我尝试添加以下文本时:
我得到以下结果:
在描述中键入的第一个字母被输入到 DataGrid 的第一个条目中,然后它会删除描述文本框中的文本。只有这样我才能继续输入我想要的内容。首字母文本框也会发生同样的事情。
有任何想法吗?如果您希望查看更多我的代码,请建议我应该添加哪一部分。
先感谢您!
最佳答案
是的,我记得遇到过这个。您必须实现 iNotifyPropertyCHnaged。这就是 viewmodel 类“通知”用户界面绑定(bind)的底层属性发生变化的方式:
看这里:
http://msdn.microsoft.com/en-us/library/ms743695.aspx
您必须为要反射(reflect)回 View 的每个属性实现此功能。所以我要做的是有一个基本的 View 模型类(ViewModelBase,它公开了 RasiePropertyChanged 方法),它实现了 iNotifyPropertyChanged,然后我的 View 模型继承自它。然后我在属性的属性集中通知属性发生了变化:
IE:
Public Property Selection As job
Get
Return Me._Selection
End Get
Set(ByVal value As job)
If _Selection Is value Then
Return
End If
_PreviousJob = _Selection
_Selection = value
RaisePropertyChanged(SelectionPropertyName)
End Set
End Property
起初这似乎令人沮丧,但需要保持 MVVM 支持的解耦。它易于实现。
关于wpf - 将项目添加到 DataGrid (MVVM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19819580/