有没有一种简单的方法来包装WPF ListBox中的文本?

时间:2016-06-03 18:44:40

标签: c# wpf xaml listbox

我一直在寻找这个,发现了一些与Winforms有关的解决方案,有些甚至只是说在WPF中很难实现,但这些帖子已经很老了。

如果我有一个标准ListBox,则声明为:

<ListBox 
    x:Name="listBox" 
    HorizontalAlignment="Left" 
    Height="240" 
    Margin="401,68,0,0" 
    VerticalAlignment="Top" 
    Width="345" 
    SelectionChanged="listBox_SelectionChanged"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    Grid.ColumnSpan="2"/>`

并以编程方式:

System.ComponentModel.BindingList<string> listItems = new System.ComponentModel.BindingList<string>();
listBox.ItemsSource = listItems;

是否有办法将这些字符串包含在ListBox

2 个答案:

答案 0 :(得分:5)

一点都不难:

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

答案 1 :(得分:0)

如果您拥有StackPanel,请摆脱它们。他们包装不好。改用GRID,就像建议的@EdPlunkett一样。

要使用此功能:

<ItemsControl ItemsSource="{Binding MyErrors, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                          Template="{StaticResource ErrorListContainerTemplate}"
                                          ItemContainerStyle="{StaticResource ErrorListStyle}"
                                         ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                                          />

这是我的样式代码:

<Style TargetType="{x:Type TextBlock}" x:Key="WrappingStyle">
    <Setter Property="TextWrapping" Value="WrapWithOverflow"/>
</Style>
<Style TargetType="ContentPresenter" x:Key="ErrorListStyle">
    <Setter Property="TextBlock.Foreground" Value="{DynamicResource TextBoxBorderErrorColor}"/>
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Border Margin="0,5">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="20" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Path Grid.Column="0" Fill="{DynamicResource TextBoxBorderErrorColor}" VerticalAlignment="Top" HorizontalAlignment="Left">
                            <Path.Data>
                                <EllipseGeometry RadiusX="2.5" RadiusY="2.5"/>
                            </Path.Data>
                        </Path>
                        <ContentPresenter Grid.Column="1" Content="{Binding}" VerticalAlignment="Top">
                            <ContentPresenter.Resources>
                                <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource WrappingStyle}"/>
                            </ContentPresenter.Resources>
                        </ContentPresenter>
                        </Grid>
                </Border>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>