Click here to Skip to main content
15,886,018 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have a WPF Application in which I am binding an ObservableCollection of integers to a ListBox in MVVM architecture, it is binding it properly, but when I select an item from the ListBox, I want to retrieve that item (or integer) and bind it to a label.

Can anybody please help me how to get SelectedIndex changed in my ViewModel using binding?

My View
<Window x:Class="DiceGameForm"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:dicegamens="clr-namespace:DiceGame"
    mc:Ignorable="d"
    Title="DiceGameForm" Height="500" Width="800" WindowStartupLocation="CenterScreen">
    <Window.DataContext>
        <dicegamens:DiceGameViewModel x:Name="_diceGameViewModel" 
           ImageSourcePath="C:\Users\Abdul.Aleem\Desktop\DiceGame\DiceGame\die1.png">
        </dicegamens:DiceGameViewModel>
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="76.988"/>
        </Grid.ColumnDefinitions>
        <ListBox x:Name="lbHistory" Margin="1.988,40.96,10,10" Grid.Column="1" FontSize="21.333" 
                 FontWeight="Bold" FontStyle="Italic" 
                 ItemsSource="{Binding Items, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                 SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                  />
        <Button x:Name="cmdClearHistory" Content="Clear" VerticalAlignment="Top" Grid.Column="1" Margin="0,13,10,0" HorizontalAlignment="Right" Width="65"/>
        <Button x:Name="cmdRollDice" Content="Roll Dice" VerticalAlignment="Top" Margin="10,13,0,0" HorizontalAlignment="Left" Width="65" Command="{Binding ClickSaveCommand, Mode=OneWay}"/>
        <Image x:Name="imgDie" Margin="10,42.97,10,10" Source="{Binding ImageSourcePath}" />
    </Grid>
</Window>


And my viewmodel
Imports System.ComponentModel
Imports System.Configuration
Imports System.Collections.ObjectModel

Public Class DiceGameViewModel
    Implements INotifyPropertyChanged, IDataErrorInfo

    Private _imageSourcePath As String
    Public Property ImageSourcePath() As String
        Get
            Return _imageSourcePath
        End Get
        Set(ByVal value As String)
            _imageSourcePath = value

            NotifyPropertyChanged("ImageSourcePath")
        End Set
    End Property

    Private _items As ObservableCollection(Of Integer)
    Public Property Items() As ObservableCollection(Of Integer)
        Get
            Return _items
        End Get
        Set(ByVal value As ObservableCollection(Of Integer))
            _items = value
            NotifyPropertyChanged("Items")
        End Set
    End Property

   
    Private _selectedItem As Integer
    Public Property SelectedItem() As Integer
        Get
            Return _selectedItem
        End Get
        Set(ByVal value As Integer)
            _selectedItem = value
            NotifyPropertyChanged("SelectedItem")
        End Set
    End Property


    Sub New()
        _items = New ObservableCollection(Of Integer)()

        _imageSourcePath = DisplayNewDiceValue(GetRandom(1, 6))
    End Sub

    Public ReadOnly Property [Error] As String Implements IDataErrorInfo.Error
        Get

        End Get
    End Property

    Default Public ReadOnly Property Item(columnName As String) As String Implements IDataErrorInfo.Item
        Get

        End Get
    End Property

    Private _clickSaveCommand As ICommand
    Public ReadOnly Property ClickSaveCommand() As ICommand
        Get
            Return If(_clickSaveCommand, (InlineAssignHelper(_clickSaveCommand, New RollDiceCommand(Sub() CmdClickRollDice(), True))))
        End Get
    End Property

    Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
        target = value
        Return value
    End Function

    Private Sub CmdClickRollDice()
        ' 'Clear history selection
        ''lbHistory.SelectedItem = Nothing

        Dim i As Integer = GetRandom(1, 6)
        DisplayNewDiceValue(i)
        DisplayHistory(i)
    End Sub


    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

    Private Sub NotifyPropertyChanged(propertyName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    ''' <summary>
    ''' Display the new image of the dice on the form
    ''' </summary>
    ''' <param name="value"></param>
    Private Function DisplayNewDiceValue(value As Integer) As String
        If (value <= 0) Then
            value = 1
        End If

        Dim ImageFolder As String = ConfigurationSettings.AppSettings.Get("ImageFolder")
        Dim sPic As String = String.Format("{0}die{1}.png", ImageFolder, value.ToString)

        Return sPic
    End Function

    ''' <summary>
    ''' Get a new random number
    ''' </summary>
    ''' <param name="Min">Minimum number to return</param>
    ''' <param name="Max">Maximum number to return</param>
    ''' <returns>integer value of random between min and max</returns>
    Private Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer

        Static Generator As System.Random = New System.Random()
        Return Generator.Next(Min, Max)

    End Function

    Private Sub DisplayHistory(value As Integer)

        _items.Add(value)

    End Sub
End Class


What I have tried:

I am trying all options on the code and searching using google while testing the application
Posted
Updated 28-May-16 21:30pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900