以编程方式将List列表绑定到ListBox [英] Programmatically binding List to ListBox
问题描述
例如我有以下非常简单的窗口:
Lets say for instance i have the following extremely simple window:
<Window x:Class="CalendarGenerator.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="447">
<Grid>
<ListBox Margin="12,40,0,12" Name="eventList" HorizontalAlignment="Left" Width="134" />
</Grid>
</Window>
一个简单的列表定义为:
And a simple list defined as:
List<String> ListOfNames = new List<String>();
让我们假设列表中有几个名字。我将如何使用尽可能多的代码隐藏列表到ListBox?
And lets assume that the list has several names in it. How would i go about binding the List to the ListBox using as much code-behind as possible?
推荐答案
首先你需要给你的ListBox一个名字,以便它可以从你的代码访问(编辑我注意到你已经这样做了,所以我将更改我的示例ListBox的名称来反映你的):
First you'd need to give your ListBox a name so that it's accessible from your code behind (edit I note you've already done this, so I'll change my example ListBox's name to reflect yours):
<ListBox x:Name="eventList" ... />
那么就像设置ListBox的 ItemsSource 属性到您的列表:
Then it's as simple as setting the ListBox's ItemsSource property to your list:
eventList.ItemsSource = ListOfNames;
由于您已将ListOfNames对象定义为列表< String> ;
,ListBox将不会自动反映对列表所做的更改。要使WPF的数据绑定对列表中的更改做出反应,请将其定义为 ObservableCollection < String>
。
Since you've defined your "ListOfNames" object as a List<String>
, the ListBox won't automatically reflect changes made to the list. To get WPF's databinding to react to changes within the list, define it as an ObservableCollection<String>
instead.
这篇关于以编程方式将List列表绑定到ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!