XAML:
<ListBox DataContext="{Binding Path=Category, Mode=OneTime}"
ItemsSource="{Binding Path=Fields}"
SelectedItem="{Binding Path=SelectedItem, Mode=OneWay}"
SelectedIndex="{Binding Path=SelectedIndex}" />
Code behind in CategoryViewModel
, the class of the Category
object from th data context:
Public ReadOnly Property Fields As ObservableCollection(Of FieldViewModel)
Get
Return m_Fields
End Get
End Property
Private ReadOnly m_Fields As New ObservableCollection(Of FieldViewModel)
Public Property SelectedIndex As Integer
Get
Return m_SelectedIndex
End Get
Set(value As Integer)
m_SelectedIndex = value
ValidateSelectedIndex()
RaisePropertyChanged("SelectedIndex")
RaisePropertyChanged("SelectedItem")
End Set
End Property
Private m_SelectedIndex As Integer = -1
Public ReadOnly Property SelectedItem As FieldViewModel
Get
Return If(m_SelectedIndex = -1, Nothing, m_Fields.Item(m_SelectedIndex))
End Get
End Property
Private Sub ValidateSelectedIndex()
Dim count = m_Fields.Count
Dim newIndex As Integer = m_SelectedIndex
If count = 0 Then
' No Items => no selections
newIndex = -1
ElseIf count <= m_SelectedIndex Then
' Index > max index => correction
newIndex = count - 1
ElseIf m_SelectedIndex < 0 Then
' Index < min index => correction
newIndex = 0
End If
m_SelectedIndex = newIndex
RaisePropertyChanged("SelectedIndex")
RaisePropertyChanged("SelectedItem")
End Sub
Public Sub New(model As Category)
' [...] Initialising of the view model,
' especially the m_Fields collection
' Auto update of SelectedIndex after modification
AddHandler m_Fields.CollectionChanged, Sub() ValidateSelectedIndex()
' Set the SelectedIndex to 0 if there are items
' or -1 if there are none
ValidateSelectedIndex()
End Sub
Now, whenever you delete an item from the m_Fields
collection, the SelectedItem
will be changed to the next item, or the previous item if the last item was removed, or Nothing
if the last remaining item was removed.