如何动态地将数据绑定到ListBox控件?

时间:2011-01-03 13:10:13

标签: c# silverlight binding windows-phone-7 listbox

我正在开发window phone 7应用程序。我是银光的新手。我试图将一个字符串列表绑定到Listbox。我使用以下代码

ObservableCollection<String> abc = new ObservableCollection<String>();
            abc.Add("XYZ");
            IncomeSummaryListBox.ItemsSource = abc;

我的xaml包含以下代码

<ListBox Margin="16,217,6,275" Name="IncomeSummaryListBox">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">

                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

使用上面的代码,我的列表框在运行时没有显示任何项目。我的模拟器设备在列表框中没有显示任何内容。我的代码有什么问题?您能否为我提供上述问题的任何代码或链接,以便我可以解决上述问题?如果我做错了什么,请指导我。

2 个答案:

答案 0 :(得分:2)

您实际上并没有告诉数据模板显示该项目。在这个简单的显示字符串的情况下,如果您只是从xaml中删除整个ListBox.ItemTemplate,它将开始工作。

出于学术原因,您可以使用: -

<ListBox Margin="16,217,6,275" Name="IncomeSummaryListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox> 

这会将Text的{​​{1}}属性绑定到ItemsSource中的项目。

答案 1 :(得分:0)

如果您想要水平而不是垂直显示项目(因为您可能正在尝试这样做),您将需要替换ItemsPanelTemplate而不是DataTemplate。

<ListBox Margin="16,217,6,275" Name="IncomeSummaryListBox">
    <ListBox.ItemsPanelTemplate >
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>
    </ListBox.ItemsPanelTemplate >
</ListBox> 
相关问题