首页 文章

使用指标在WPF ListBox中约束项高度

提问于
浏览
0

我在WPF中有一个ListBox控件,它包含可变高度的项(主要是一个大的文本块,所以它也受到自动换行的影响) . 由于当单个项目的高度过高时(特别是当接近ListBox本身的高度时)滚动表现很差,我想约束各个项目的最大高度 .

通过使用Style来设置ListBoxItem容器的MaxHeight,我已经足够了 .

我的问题是我想检测到一个单独的项目已经达到了这个约束,然后以不同的方式设置它 .

这是我的第一次尝试:

<Style x:Key="LogContainerStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="MaxHeight" Value="64" />
    <EventSetter Event="MouseDoubleClick" Handler="LogEntry_MouseDoubleClick" />
</Style>
<DataTemplate x:Key="LogTemplate">
    <Grid>
        <TextBlock Text="{Binding Message}" />
        <TextBlock x:Name="More" Text="(more)"
                   HorizontalAlignment="Right" VerticalAlignment="Bottom"
                   Foreground="DarkGray" Visibility="Collapsed" />
    </Grid>
    <DataTemplate.Triggers>
        <Trigger ... height capped at MaxHeight? ...>
            <Setter TargetName="More" Property="Visibility" Value="Visible" />
        </Trigger>
    </DataTemplate.Triggers>
</DataTemplate>

但我不知道如何编写触发器 . 备选方案欢迎 .

1 回答

  • 1

    请尝试下面的代码 . 我将ListBoxItem.MaxHeight设置为99.然后我在DataTemplate中添加了一个触发器,用于检查模板中根元素的ActualHeight(即下面的“bd”),如果它是99,我更改了BorderBrush . 希望这可以帮助 .

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication1"
            xmlns:sys="clr-namespace:System;assembly=mscorlib"
            ShowActivated="False"
            Title="MainWindow" Height="350" Width="525">
        <ListBox x:Name="lb">
            <ListBox.ItemsSource>
                <x:Array Type="{x:Type sys:Double}">
                    <sys:Double>250</sys:Double>
                    <sys:Double>100</sys:Double>
                    <sys:Double>50</sys:Double>
                    <sys:Double>25</sys:Double>
                    <sys:Double>99</sys:Double>
                    <sys:Double>120</sys:Double>
                </x:Array>
            </ListBox.ItemsSource>
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="MaxHeight" Value="99"/>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border x:Name="bd" BorderBrush="Black" BorderThickness="1">
                        <TextBlock Text="{Binding}" Height="{Binding}" Background="LightGray"/>
                    </Border>
                    <DataTemplate.Triggers>
                        <Trigger SourceName="bd" Property="ActualHeight" Value="99">
                            <Setter TargetName="bd" Property="BorderBrush" Value="Red"/>
                        </Trigger>
                    </DataTemplate.Triggers>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Window>
    

相关问题