WPF - 非常基本的 ListBox.ItemTemplate 问题 [英] WPF - Very basic ListBox.ItemTemplate Question
问题描述
好的,这是一个看起来很简单的问题,但让我发疯了.我正在学习 DataTemplating,并尝试将一个非常简单的 ItemTemplate 应用到 ListBox.
Ok, this is an embarassingly simple-looking problem, but is driving me crazy. I'm learning about DataTemplating and am trying to apply a very VERY simple ItemTemplate to a ListBox.
但是,当我运行我的应用程序时,模板完全被忽略了,我只得到了标准外观的列表框,而实际上我希望看到一个带有测试"的复选框列表.
However, when I run my app, the template is completely ignored and I just get the standard-looking listbox, whereas in fact I'd expect to see a list of checkboxes with 'Test' along side.
我已经尝试了几次,结果总是一样.我在 Google 上检查了几个资源,并且在 ListBox 上定义和 ItemTemplate 的语法都相同,所以我真的看不出哪里出错了.
I've tried this several times and always the same result. I've checked several resource on Google and all have the same kind of syntax for defining and ItemTemplate on a ListBox, so I really cannot see where I'm going wrong.
代码...
<Grid x:Name="LayoutRoot">
<ListBox x:Name="TestList"
SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox Content="Check this checkbox!"/>
<TextBlock>Test</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Items>
<ListBoxItem>Bob</ListBoxItem>
<ListBoxItem>Jim</ListBoxItem>
<ListBoxItem>Dave</ListBoxItem>
<ListBoxItem>Larry</ListBoxItem>
<ListBoxItem>Tom</ListBoxItem>
</ListBox.Items>
</ListBox>
</Grid>
非常感谢任何帮助.抱歉,这个看似愚蠢的问题,但我真的在这里的第一个障碍:(
Any help greatly appreciated. Sorry for such a dumb-seeming question, but I've really fallen at the first hurdle here :(
在
推荐答案
ItemTemplate
将 ListBoxItem
直接作为 item 时不起作用.一般概念是将 CRL 集合数据绑定到 ListBox.ItemsSource
,然后指定 ItemTemplate
.检查下面的代码.
ItemTemplate
wont work when you put ListBoxItem
directly as items. General concept is you databind a CRL collection to the ListBox.ItemsSource
and then specify the ItemTemplate
. Check the below code.
<Grid x:Name="LayoutRoot">
<ListBox x:Name="TestList" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox Content="Check this checkbox!"/>
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Items>
<sys:String>Bob</sys:String>
<sys:String>Jim</sys:String>
<sys:String>Dave</sys:String>
<sys:String>Larry</sys:String>
<sys:String>Tom</sys:String>
</ListBox.Items>
</ListBox>
</Grid>
其中 sys
是 xmlns:sys="clr-namespace:System;assembly=mscorlib"
这样,在后台生成了5个ListBoxItems
并添加到ListBox
中.
In this way, there are 5 ListBoxItems
getting generated in the background and added to the ListBox
.
这篇关于WPF - 非常基本的 ListBox.ItemTemplate 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!