gpt4 book ai didi

c# - 使用 ItemsSource 和 ItemTemplate 的 WPF 列表框

转载 作者:行者123 更新时间:2023-11-30 14:10:21 27 4
gpt4 key购买 nike

当我同时拥有 ItemsSource 时,我对如何解析绑定(bind)感到困惑和一个 ItemTemplate在 WPF 中 ListBox .

我有一个 ObservableCollection<int>称为 ListOfIndexes .对于每个索引,我想在数据库表中查找它的记录。我希望在 IndexToObjectDescriptionConverter 中做到这一点.

<ListBox ItemsSource="{Binding ListOfIndexes}" 
ItemTemplate="{Binding Converter={StaticResource IndexToObjectDescriptionConverter}}" />

但是转换器中的断点告诉我 ItemTemplate 正在读取的值绑定(bind)是窗口本身的——即 DataContextItemsSourceItemsTemplate是一样的。

请原谅我有点直率,但这看起来很愚蠢。整点ItemTemplate是渲染 ItemsSource 中的每个元素,所以我想我认为 DataContextItemTemplate将是正在呈现的单个元素。

那么,就是说,我该如何告诉 ItemTemplate它应该担心由 ItemsSource 表示的各个元素而不是使用整个窗口的 DataContext

最佳答案

您需要为 ItemTemplate 使用数据模板。然后将其应用于列表中的每个项目

MSDN 文档在这里: http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplate(v=vs.110).aspx

她的问题是关于数据上下文范围。当您在 ListBox 上绑定(bind)任何属性时,它将使用 ListBox 的数据上下文——这就是为什么将数据上下文传递给转换器的原因。如果您在 ItemTemplate 中设置数据模板,它将将该模板应用于列表中的每个项目。我想根据您提供的简单代码,您需要在数据模板中安装转换器:

<ListBox ItemsSource="{Binding ListOfIndexes}">
<ListBox.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding Converter={StaticResource IndexToObjectDescriptionConverter}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

在这种情况下,将为每个项目呈现 ContentControl,并将该项目作为其数据上下文。

关于c# - 使用 ItemsSource 和 ItemTemplate 的 WPF 列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24411699/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com