0
votes

I'm a new in WPF. I have created a ListBox

<ListBox 
  Name="listBoxQuestion" 
  Grid.Row="1" Margin="3" 
  SelectionMode="Single" 
  MouseDown="listBoxQuestion_MouseDown" 
  SelectionChanged="listBoxQuestion_SelectionChanged" 
  DisplayMemberPath="Text">
</ListBox>

and I use listBoxQuestion.SelectedIndex to get index of selected item. But it only work once, the first time I click on item. When I click on other item, the index isn't changed. It still keep current value. I can't find what's wrong in my code. Please help me!

Update

There are my itemsource

public class ListTopicBinding : ObservableCollection<Question>
{
}

ListQuestionBinding listQuestionShowing = new ListQuestionBinding();

listBoxQuestion.ItemsSource = listQuestionShowing;

When I create new item I use code

Question q = new Question();
q.Text = "*";
listQuestionShowing.Add(q);

I have found that when I delete function in Question class

public override int GetHashCode()
    {
        return this.Text.GetHashCode();
    }

My ListBox work correctly. I wonder that how "GetHashCode" func affect ListBox in WPF. I used this code in WinForm, but nothing happened. Sorry for my English

2
What is your code-behind? - user2153378
Where is ItemsSource set? - Rohit Vats
Why would you bind to DisplayMemberPath in XAML but not ItemsSource. Show your binding and implement INotifyPropertyChanged. - paparazzo
Make ListTopicBinding a public property ( get ) and bind in xaml. - paparazzo

2 Answers

0
votes

Is it this you want?

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        listBoxQuestion.ItemsSource = new List<String> { "AAA", "BBB", "CCC" };
    }

    private void listBoxQuestion_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show("You selected " + listBoxQuestion.SelectedItem.ToString());
    }
0
votes

Names don't match up in the question

ItemsSource="{Binding Path=listTopicBinding}"
DisplayMemberPath="Text"

private ListTopicClass listTopicBinding = new ListTopicClass();
public ListTopicBinding 
{
   get { return listTopicBinding ; }
}