How to bind data to ListBox Control dynamically?

怎甘沉沦 提交于 2019-12-13 02:29:04

问题


I am developing window phone 7 application. I am new to the silverlight. I am trying to bind a List of strings to Listbox. I am using the following code

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

My xaml contains the following code

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

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

With the above code my listbox shows no items at runtime. My emulator device doesn't show anything in listbox. What is wrong in my code ? Can you please provide me any code or link for the above issue so that I can resolve the above issue ? If I am doing anything wrong then please guide me.


回答1:


You've not actually told the data template to display the item. In this simple case of displaying strings if you just delete the whole ListBox.ItemTemplate from your xaml it will start working.

For academic reasons you could use:-

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

This binds the Text property of a TextBlock to an item from the ItemsSource.




回答2:


If you are wanting to display your items horizontally instead of vertically (as it looks like you may be trying to do), you'll want to replace the ItemsPanelTemplate instead of the DataTemplate.

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


来源:https://stackoverflow.com/questions/4584687/how-to-bind-data-to-listbox-control-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!