|
Hi All,
Just writing in WPF for the first time, and I ran into this situation:
I'm attempting to load a combobox with values from a dataset without writing anything in codebehind (as per the MVVM way). Many things I have tried failed. Here's the latest:
The Model:
[ol]
Public Class ChainTableModel
Dim _chainId As String
Dim _chainType As String
Public Property ChainId As String
Get
Return _chainId
End Get
Set(value As String)
_chainId = value
End Set
End Property
Public Property ChainType As String
Get
Return _chainType
End Get
Set(value As String)
_chainType = value
End Set
End Property
Public Sub New(chainId As String, chainType As String)
_chainId = chainId
_chainType = chainType
End Sub
End Class
[/ol]
The ViewModel:
[ol]
Public Class ChainViewModel
Implements INotifyPropertyChanged
Dim _chainTypes As ObservableCollection(Of ChainTableModel) = New ObservableCollection(Of ChainTableModel)()
Public Property ChainTypes As ObservableCollection(Of ChainTableModel)
Get
If _chainTypes.Count = 0 Then DBLoadChains()
Return _chainTypes
End Get
Set(value As ObservableCollection(Of ChainTableModel))
_chainTypes = value
NotifyPropertyChanged("ChainTypes")
End Set
End Property
Private Sub DBLoadChains()
For Each row As DataRow In CatCollections.dsChains.Tables("ChainTable").Rows
Dim display As String = row("Name").ToString
Dim value As String = row("id").ToString
If display = String.Empty Then display = value
_chainTypes.Add(New ChainTableModel(value, display))
Next
End Sub
Private Sub NotifyPropertyChanged(propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
End Class
[/ol]
The XAML:
[ol]
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CatLayoutTools"
Title="CatScript Layout Tools (WPF) - Chain Options" SizeToContent="WidthAndHeight" Height="Auto"
ResizeMode="NoResize" Width="Auto">
[/ol]
When I run the code, the combobox is populated with the following text "CatLayoutTools.ChainTableModel" the number of times as there are rows in the database query.
What am I missing here? I'm trying to accomplish the combobox loading and selecting of current item the MVVM way: Binding to a ViewModel.
Also, I have a question: as you can see, I am loading my observablecollection with data from the dataset in the viewmodel in the 'ChainTypes' property Get. Somehow I don't think this is the right place to do this, but then if I put a constructor in the viewmodel, the "" line in the XAML bugs out, telling me that object is not set to an instance of...
And if I handle the loading of observablecollection from my AutoCAD initialization sub, how do I preserve the observablecollection for when it is needed to be bound to combobox?
Any help is appreciated.
Thanks, |
|