【问题标题】:WPF Listbox selectedindex not working <no change>WPF Listbox selectedindex 不工作 <无变化>
【发布时间】:2014-11-29 11:12:10
【问题描述】:

我是 WPF 的新手。我创建了一个列表框

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

我使用 listBoxQuestion.SelectedIndex 来获取所选项目的索引。但它只工作一次,我第一次点击项目。当我点击other item时,索引没有改变。它仍然保持当前值。我找不到我的代码有什么问题。请帮帮我!

更新

有我的物品来源

public class ListTopicBinding : ObservableCollection<Question>
{
}

ListQuestionBinding listQuestionShowing = new ListQuestionBinding();

listBoxQuestion.ItemsSource = listQuestionShowing;

当我创建新项目时,我使用代码

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

我发现当我删除问题类中的函数时

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

我的 ListBox 工作正常。我想知道“GetHashCode”函数如何影响WPF中的ListBox。我在 WinForm 中使用了这段代码,但什么也没发生。 对不起我的英语

【问题讨论】:

  • 你的代码隐藏是什么?
  • ItemsSource 设置在哪里?
  • 为什么要绑定到 XAML 中的 DisplayMemberPath 而不是 ItemsSource。显示您的绑定并实施 INotifyPropertyChanged。
  • 使 ListTopicBinding 成为公共属性 ( get ) 并在 xaml 中绑定。

标签: c# wpf listbox


【解决方案1】:

问题中的名称不匹配

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

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

【讨论】:

    【解决方案2】:

    这是你想要的吗?

        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());
        }
    

    【讨论】:

    • 为什么投反对票?因为它不在 MVVM 中?此外,自从我 11 小时前给出答案以来,这个问题已经发生了很大变化......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    相关资源
    最近更新 更多