【发布时间】:2017-04-13 18:34:05
【问题描述】:
我正在尝试使用 ListBox 选择一个条目,然后显示属于该所选条目的图片。但是刚开始我遇到了第一个问题:使用绑定填充 ListBox 是有效的,但是如果我在正在运行的程序中单击一行,它不会选择该行。我只能看到突出显示的悬停效果,但不能选择一行。任何想法我的错误可能是什么?
这是我的 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 中,我正在用条目填充 ListBox:
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 已正确填充,但没有选择任何内容 - 所以我无法继续加载与所选条目匹配的图片。 我对编程还是很陌生,所以任何帮助都会很棒:)
编辑:如果有人稍后再看这个帖子:这是 - 非常明显的 - 解决方案
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;
还有新的类DataItem:
class DataItem
{
private String text;
public DataItem(String s)
{
text = s;
}
public String Text
{
get
{
return text;
}
}
}
【问题讨论】:
标签: c# wpf xaml listbox selection