将项绑定到ListBox多列

我正在尝试将我的数据添加到多个列ListBox中,我做到了但是我在尝试从列表框中检索数据时遇到了一个难题。 有没有办法将对象而不是文本放入listBox行?

             

这是代码

  public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public sealed class MyListBoxItem { public string Field1 { get; set; } public string Field2 { get; set; } public string Field3 { get; set; } } private void Window_Loaded(object sender, RoutedEventArgs e) { Students st = new Students(1, "name","anything"); listBox1.ItemsSource = new List(new[] { st }); } private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e) { object ob = listBox1.SelectedItem; string i = ((MyListBoxItem)listBox1.SelectedItem).Field1; } } 

这是class级学生

  class Students { int id; string name; string f; public Students(int id, string name,string f) { this.id = id; this.name = name; this.f = f; } public int ID { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public string F { get { return f; } set { f = value; } } } 

不要使用listBox1.Items.Add(….)。 而是使用listBox1.ItemsSource = new List(new [] {st});

然后将您的DisplayMemberBindings分别更改为“Id”,“Name”。

不需要ListBoxItem类。

==编辑==

你非常接近完美。 我在下面附上它应该如何工作。 需要注意的重要事项是ListView for ItemsSource和SelctedITem中的Bindings,以及将IsSynchronisedWithCurrentItem设置为true。

此外,在网格的底部两行中,我展示了两种不同的绑定方式,一种使用“/”符号,另一种使用ViewModel上的属性

XAML

                    ID    ID     

Main.Window.cs

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace StackOverflow11087468 { ///  /// Interaction logic for MainWindow.xaml ///  public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new ViewModel(); } } } 

ViewModel.cs

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using System.ComponentModel; namespace StackOverflow11087468 { public class ViewModel : INotifyPropertyChanged { public ObservableCollection Students { get; set; } public ViewModel() { this.Students = new ObservableCollection(); Students.Add(new Student(98760987, "Student1", "F")); Students.Add(new Student(98760988, "Student22", "M")); } public Student SelectedStudent { get { return _selectedStudent; } set { _selectedStudent = value; RaisePropertyChanged("SelectedStudent"); } } private void RaisePropertyChanged(string propertyName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; private Student _selectedStudent; } }