单击时填充了绑定的列表框没有 select 项

ListBox filled with binding doesn't select item on click

我正在尝试使用 ListBox 选择一个条目,然后显示属于这个 selected 条目的图片。但就在一开始,我遇到了第一个问题:用绑定填充 ListBox 是可行的,但如果我单击我的 运行 程序中的一行,它不会 select 该行。我只能看到突出显示的悬停效果,但看不到 select 一行。知道我的错误可能是什么吗?

这是我的 XAML:

        <ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontSize="24"/>

在 MainWindow.xaml.cs 中,我正在用条目填充列表框:

private void fillEntrySelectionListBox()
    {
        //Fill listBox with entries for active user
        DataContext = this;
        entryItems = new ObservableCollection<ComboBoxItem>();
        foreach (HistoryEntry h in activeUser.History)
        {
            var cbItem = new ComboBoxItem();
            cbItem.Content = h.toString();
            entryItems.Add(cbItem);
        }
        this.entrySelection.ItemsSource = entryItems;
        labelEntrySelection.Text = "Einträge für: " + activeUser.Id;

        //show image matching the selected entry
        if (activeUser.History != null)
        {
            int index = entrySelection.SelectedIndex;
            if (index != -1 && index < activeUser.History.Count)
            {
                this.entryImage.Source = activeUser.History[index].Image;
            }
        }
    }

所以我可以看到我的 ListBox 已正确填充,但没有 select 任何东西 - 所以我无法继续加载与 selected 条目匹配的图片。 我对编程还是很陌生,所以任何帮助都会很棒:)


编辑:如果有人稍后查看此线程:这是 - 非常明显的 - 解决方案

XAML 现在看起来像这样

<ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontFamily="Siemens sans" FontSize="24">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Text}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

后面的代码来填充它:

//Fill listbox with entries for selected user
DataContext = this;
entryItems = new ObservableCollection<DataItem>();
foreach (HistoryEntry h in selectedUser.History)
{
    var lbItem = new DataItem(h.toString());
    entryItems.Add(lbItem);
}
this.entrySelection.ItemsSource = entryItems;
labelEntrySelection.Text = "Einträge für: " + selectedUser.Id;

和新的 Class 数据项:

class DataItem
{
    private String text;

    public DataItem(String s)
    {
        text = s;
    }

    public String Text
    {
        get 
        { 
            return text; 
        }
    }
}

您正在用 ComboBoxItem 填充它,这与 ListBox 无关,而且根据定义也是错误的。

您需要让 ObservableCollection 充满数据项。

意思是,做一个class包含你要存储的数据,ListBox会自动为每个数据项生成一个ListBoxItem。

http://www.wpf-tutorial.com/list-controls/listbox-control/