Sam King Sam King - 1 year ago 230
C# Question

listbox selected item returning Null value

I have a listbox which is binded to a Viewmodel, i am using mouse_doubeclickevent to retrieve the selected item value but its returning null, what i could be missing here ? SWdistinct is a list

ViewModel:

public List<swversion> SWdistinct
{
get;
set;
}


XAML:

<ListBox x:Name="CRSWUNIQUE" ItemsSource="{Binding SWdistinct}" SelectedItem="{Binding Path=SWdistinct,Mode=TwoWay}" MouseDoubleClick="CRSWUNIQUE_MouseDoubleClick" DisplayMemberPath="SW_Version" IsTextSearchEnabled="True" />


Code Behind:

private void CRSWUNIQUE_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
ListBoxItem item = CRSWUNIQUE.SelectedItem as ListBoxItem;
if (item != null)
// if (CRSWUNIQUE.SelectedItem != null)
{
MessageBox.Show(item.Content.ToString());
}
}

Answer Source

SelectedItem will give the object you bound. In this case it would be the object of swversion. Try below code.

private void CRSWUNIQUE_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
   var swversionitem = CRSWUNIQUE.SelectedItem as swversion;
    if (swversionitem != null)
       // if (CRSWUNIQUE.SelectedItem != null)
    {            
        MessageBox.Show(swversionitem.SW_Version.ToString());
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download