使用ItemsSource和ItemTemplate的WPF ListBox [英] WPF ListBox using ItemsSource and ItemTemplate
问题描述
当我在WPF ListBox
中同时具有ItemsSource
和ItemTemplate
时,我对如何解析绑定感到困惑.
I'm confused as to how bindings are resolved when I have both an ItemsSource
and an ItemTemplate
in a WPF ListBox
.
我有一个名为ListOfIndexes
的ObservableCollection<int>
.对于每个索引,我想在数据库表中查找其记录.我希望在IndexToObjectDescriptionConverter
中做到这一点.
I have an ObservableCollection<int>
called ListOfIndexes
. For each index, I want to look up its record in a database table. I hope to do that in the IndexToObjectDescriptionConverter
.
<ListBox ItemsSource="{Binding ListOfIndexes}"
ItemTemplate="{Binding Converter={StaticResource IndexToObjectDescriptionConverter}}" />
但是转换器中的断点告诉我,ItemTemplate
绑定读取的值是窗口本身的—.即ItemsSource
和ItemsTemplate
的DataContext
是相同的.
But a breakpoint in the converter is telling me that the value being read in by the ItemTemplate
binding is of the window itself — i.e., the DataContext
of the ItemsSource
and ItemsTemplate
is the same.
请原谅一些,但这似乎是愚蠢的. ItemTemplate
的全部要点是渲染ItemsSource
中的每个元素,所以我想我认为ItemTemplate
的DataContext
是要渲染的单个元素.
Pardon a bit of candidness, but this seems DUMB. The entire point of the ItemTemplate
is to render each element within the ItemsSource
, so I guess I figured that the DataContext
of the ItemTemplate
would be the individual element being rendered.
也就是说,我如何告诉ItemTemplate
它应该担心由ItemsSource
表示的各个元素,而不要使用整个窗口的DataContext
?
So, that said, how do I tell the ItemTemplate
that it should worry about the individual elements represented by the ItemsSource
and not use the entire window's DataContext
?
推荐答案
您需要为ItemTemplate使用数据模板.然后将其应用于列表中的每个项目
You need to use a data template for the ItemTemplate. This is then applied to each item in the list
MSDN docs are here: http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplate(v=vs.110).aspx
她的问题与数据上下文范围有关.当您在ListBox上绑定任何属性时,它将使用ListBox的数据上下文-因此,为什么要将该数据上下文传递给转换器.如果您在ItemTemplate中设置数据模板,它将将该模板应用于列表中的每个项目.我想根据您提供的简单代码,您需要将转换器包含在数据模板中:
The issue her is about data context scope. When you bind any property on the ListBox, it will use the data context of the ListBox - hence why that data context is being passed to the converter. If you set a data template inside the ItemTemplate, it will apply that template to each item in the list. I guess based on the simple code you've provided you would need to have the converter inside the data template:
<ListBox ItemsSource="{Binding ListOfIndexes}">
<ListBox.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding Converter={StaticResource IndexToObjectDescriptionConverter}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在这种情况下,将为每个项目呈现ContentControl,并将该项目作为数据上下文.
In this case, the ContentControl will be rendered for each item, with that item as it's data context.
这篇关于使用ItemsSource和ItemTemplate的WPF ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!