I was very unpleasant surprised to find out that there is no selectedvalue property for a combobox in Silverlight 3. Most of the time you want to perform an action based on a combo box selection change. So, I come up with a simple solution which will be detailed below.
XAML code:
<ComboBox x:Name="MyColors">
We need two simple classes to bind the combobox:
Public Class CComboItem
Private _ID
As Int64
Private _Description
As String
Public Sub New(
ByVal pid
As Int64,
ByVal pDesc
As String)
_ID = pid
_Description = pDesc
End Sub
Public Property ID()
As Int64
Get
Return _ID
End Get
Set(
ByVal value
As Int64)
_ID = value
End Set
End Property
Public Property Description()
As String
Get
Return _Description
End Get
Set(
ByVal value
As String)
_Description = value
End Set
End Property
End Class
Second class, more exactly a collection:
Imports System.Collections.ObjectModel
Public Class CComboList
Inherits ObservableCollection(Of CComboItem)
Public Sub addItem(ByVal itm As CComboItem)
Add(itm)
End Sub
End Class
Load the combo as follows:
Dim colorList As New CComboList
colorList.Add(New CComboItem(1, "red"))
colorList.Add(New CComboItem(2, "yellow"))
colorList.Add(New CComboItem(3, "blue"))
MyColors.ItemsSource = colorList
MyColors.DisplayMemberPath = "Description"
MyColors.SelectedIndex = 0
Finally, because the post is already too long, get selected value from the combo box:
Private Sub MyColors_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles MyColors.SelectionChanged
Dim id As Int64
If MyColors.SelectedItem Is Nothing Then Exit Sub
' here is the selected value...
id = DirectCast(MyColors.SelectedItem, CComboItem).ID
End Sub
Pretty simple, but at least is doing the trick.