C# 列表框中填充的绑定不';单击时不要选择项目
我正在尝试使用列表框选择一个条目,然后显示属于此选定条目的图片。但刚开始我就遇到了第一个问题:用绑定填充列表框是可行的,但是如果我在运行的程序中单击一行,它就不会选择该行。我只能看到高亮显示的悬停效果,但不能选择一条线。知道我的错误是什么吗 这是我的XAML:C# 列表框中填充的绑定不';单击时不要选择项目,c#,wpf,xaml,listbox,selection,C#,Wpf,Xaml,Listbox,Selection,我正在尝试使用列表框选择一个条目,然后显示属于此选定条目的图片。但刚开始我就遇到了第一个问题:用绑定填充列表框是可行的,但是如果我在运行的程序中单击一行,它就不会选择该行。我只能看到高亮显示的悬停效果,但不能选择一条线。知道我的错误是什么吗 这是我的XAML: <ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="
<ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontSize="24"/>
您正在用ComboBoxItem填充它,它与ListBox不相关,而且根据定义也是错误的 您需要用数据项填充ObservableCollection 也就是说,创建一个包含要存储的数据的类,ListBox将自动为每个数据项生成ListBoxItem
哦,谢谢你的提示-这是一个复制粘贴错误。我会试试:)是的,现在它起作用了-我现在感觉很笨^^谢谢你的帮助:)
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 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 DataItem
{
private String text;
public DataItem(String s)
{
text = s;
}
public String Text
{
get
{
return text;
}
}
}