我在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>
但我不确定如何编写触发器。欢迎替代方案。
答案 0 :(得分: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>