WPF - 非常基本的 ListBox.ItemTemplate 问题

标签 wpf listbox datatemplate itemtemplate

好的,这是一个看起来很简单的问题,但让我发疯。我正在学习 DataTemplating,并试图将一个非常简单的 ItemTemplate 应用于 ListBox。

但是,当我运行我的应用程序时,模板被完全忽略了,我只得到了标准外观的列表框,而实际上我希望看​​到一个带有“测试”的复选框列表。

我已经尝试了几次,结果总是一样。我在 Google 上检查了几个资源,并且在 ListBox 上定义和 ItemTemplate 的语法都相同,所以我真的看不出哪里出错了。

代码...

<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>

非常感谢任何帮助。对不起,这个看似愚蠢的问题,但我真的在这里遇到了第一个障碍:(

最佳答案

ItemTemplateListBoxItem 时不起作用直接作为元素。一般概念是将 CRL 集合数据绑定(bind)到 ListBox.ItemsSource然后指定 ItemTemplate .检查下面的代码。

 <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>

在哪里 sysxmlns:sys="clr-namespace:System;assembly=mscorlib"
这样一来就有5个ListBoxItems在后台生成并添加到 ListBox .

关于WPF - 非常基本的 ListBox.ItemTemplate 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2456643/

相关文章:

c# - ListView mvvm中的WPF删除按钮

c# - 将文本框值添加到数组并将其显示在列表框中。单击按钮时刷新数组

python - 在 Python 3.5 中同时从不同的 Tkinter Listbox 小部件中选择值

Xamarin 表单中的 ListView 数据模板绑定(bind)

c# - 列表框中的 WPF 数据模板多态性

C# WPF框架中的Page和MainWindow之间的数据交换

c# - 我可以在 .NET 3.5 的代码隐藏中打印标准测试页吗?

c# - 以编程方式从资源字典中添加删除项目

c# - 无法让 ListBox 和 UpdateTarget 工作

wpf - 数据模板 + MVVM