windows phone 7 TextBlock TextWrapping not honored in listbox

你离开我真会死。 提交于 2019-12-23 19:56:48

问题


I have a listbox defined as :

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <ListBox x:Name="myListBox" Width="468" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <toolkit:WrapPanel />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.Template>
                <ControlTemplate>
                    <ScrollViewer Width="468">
                        <ItemsPresenter />
                    </ScrollViewer>
                </ControlTemplate>
            </ListBox.Template>
        </ListBox>
    </Grid>

In the code, I create multiple textBlocks as the Listbox Items with textWrapping enabled in each textBlock.

       for (int i = 0; i < everyLine.Length; i++)
        {
            TextBlock txtBlock = new TextBlock()
            {
                TextWrapping = TextWrapping.Wrap,
                Name = "textBlock" + i,
                Foreground = textBrush,
                FontSize = 20,
                Text = everyLine[i]
           };

            this.myListBox.Items.Add(txtBlock);
        }

But, none of the text in any of the text blocks gets wrapped.

Can somebody please let me know if the above way of defining textBlocks in listbox is incorrect?


回答1:


+1 for Derek's answer

Also, please be careful using the <StackPanel> in your ListBox. By default, the ListBox uses a <VirtualizingStackPanel> and this is very important as it uses significantly less UI resources (memory) when displaying long lists.




回答2:


Is there any particular reason why you are adding elements in code? By the looks of things you have a data collection, which you can set ast teh ItemsSource of the ListBox and then use an ItemTemplate to specify what each item should look like. Something like the following:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <ListBox x:Name="myListBox" Width="468">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock FontSize="20" Text="{Binding}" TextWrapping="Wrap" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

Note, that the default style for the ListBox already includes the ScrollViewer so there's no need to change the ControlTemplate. Because you've already fixed the width of the ListBox, the above should "just work".



来源:https://stackoverflow.com/questions/5440452/windows-phone-7-textblock-textwrapping-not-honored-in-listbox

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