在Listbox项目中包装文本

时间:2016-09-26 10:00:08

标签: c# wpf listbox

问题

我有一个列表框,我已经绑定到 ObservableCollection<串GT;

Polls = new ObservableCollection<string>();

DataSet LoadAllPolls = _publisher.GetQuizFeatures(Global.gEpisodeWS.Id);

foreach (DataRow item in LoadAllPolls.Tables[0].Rows)
{
    Polls.Add(item["Description"].ToString());
}

这是XAML:

<ListBox x:Name="lb_polls" Background="#ececec" BorderBrush="Transparent" SelectedItem="{Binding SelectedPoll}" ItemsSource="{Binding Polls}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Height" Value="110"/>
            <Setter Property="Width" Value="200"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#858585" />
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#858585" />
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="#858585"/>
    </ListBox.Resources>
</ListBox>

现在我希望将要添加到ListBox项目的字符串换行。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

添加此ItemTemplate:

<ListBox.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding}" TextWrapping="Wrap"/>
    </DataTemplate>
</ListBox.ItemTemplate>

答案 1 :(得分:1)

这很简单,但我不知道为什么不运行你的代码,这是xaml

<Grid Width="600" Height="Auto" >
        <ListBox  ItemsSource="{Binding Polls}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="Height" Value="110"/>
                    <Setter Property="Width" Value="200"/>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" TextWrapping="Wrap"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

绑定到ObservableCollection民意调查并且工作正常。

       private void LoadPoll()
        {
            for (int i = 1; i <= 3; i++)
            {
                Polls.Add("Poll" + i.ToString());
            }
        }

        private ObservableCollection<string> _Polls = new ObservableCollection<string>();
        public ObservableCollection<string> Polls
        {
            get { return _Polls; }
            set
            {
                _Polls = value;
            }
        }