以编程方式将 List 绑定到 ListBox [英] Programmatically binding List to ListBox
问题描述
比方说,例如,我有一个非常简单的窗口:
Let's 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>();
让我们假设列表中有几个名字.我将如何使用尽可能多的代码隐藏将 List 绑定到 ListBox?
And let's 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"对象定义为 List
,ListBox 不会自动反映对列表所做的更改.要让 WPF 的数据绑定对列表中的更改做出反应,请将其定义为 ObservableCollection
代替.
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屋!