将文本换行到列表框项中

本文关键字:列表 文本 换行 | 更新日期: 2023-09-27 18:08:53

问题


我有一个列表框,我已将其绑定到ObservableCollection<string>:

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项中的字符串换行。我该怎么做?

将文本换行到列表框项中

这很简单,但我不知道为什么不能处理你的代码,这是我的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>

其绑定到CCD_ 2轮询并且工作良好。

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

添加此ItemTemplate:

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