以编程方式将List绑定到ListBox
让我们说比如我有以下非常简单的窗口:
一个简单的列表定义为:
List ListOfNames = new List();
并且假设列表中有多个名称。 我如何使用尽可能多的代码隐藏将List绑定到ListBox?
首先,你需要给你的ListBox一个名字,以便可以从后面的代码访问它( 编辑我注意你已经完成了这个,所以我将更改我的示例ListBox的名称以反映你的名字):
然后就像将ListBox的ItemsSource属性设置为列表一样简单:
eventList.ItemsSource = ListOfNames;
由于您已将“ListOfNames”对象定义为List
,因此ListBox不会自动反映对列表所做的更改。 要使WPF的数据绑定对列表中的更改做出反应,请将其定义为ObservableCollection
。
如果数据列表是在代码中创建的,那么您将不得不在代码中绑定它,如下所示:
eventList.ItemsSource = ListOfNames;
现在绑定到字符串列表是一个非常简单的例子。 让我们采取更复杂的一个。
假设你有一个人类:
public class Person { public string FirstName { get; set; } public string Surname { get; set; } }
要显示一个列表,您可以将列表绑定到ListBox,但最终会出现一个列表框,显示每个条目的“Person”,因为您没有告诉WPF如何显示person对象。
为了告诉WPF如何直观地显示数据对象,我们定义了一个DataTemplate,如下所示:
public Window1() { InitializeComponent(); List people = new List (); people.Add(new Person() { FirstName = "Cameron", Surname = "MacFarland" }); people.Add(new Person() { FirstName = "Bea", Surname = "Stollnitz" }); people.Add(new Person() { FirstName = "Jason", Surname = "Miesionczek" }); listBox.ItemsSource = people; }
这将在列表中很好地显示“Firstname Surname”。
如果你想将外观更改为“ Surname ,Firstname”,你需要做的就是将XAML更改为:
如果要自定义绑定,请使用Binding类:
List listOfNames = new List () {"a", "b"}; Binding myBinding = new Binding(); //set binding parameters if necessary myBinding.Source = listOfNames; eventList.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);
要么
直接将数据分配给ItemsSource属性:
eventList.ItemsSource = listOfNames;
eventList.ItemsSource = ListOfNames;