您可以在ListBox上設置一個樣式,它根據項目數切換ItemTemplate。
<ListBox ItemsSource="{Binding Items}">
<ListBox.Resources>
<local:SizeConverter x:Key="SizeConverter"/>
<DataTemplate x:Key="SmallTemplate"></DataTemplate>
<DataTemplate x:Key="MediumTemplate"></DataTemplate>
<DataTemplate x:Key="LargeTemplate"></DataTemplate>
</ListBox.Resources>
<ListBox.Style>
<Style TargetType="ListBox">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Items.Count, Converter={StaticResource SizeConverter}}" Value="Small">
<Setter Property="ItemTemplate" Value="{StaticResource SmallTemplate}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=Items.Count, Converter={StaticResource SizeConverter}}" Value="Medium">
<Setter Property="ItemTemplate" Value="{StaticResource MediumTemplate}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=Items.Count, Converter={StaticResource SizeConverter}}" Value="Large">
<Setter Property="ItemTemplate" Value="{StaticResource LargeTemplate}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Style>
</ListBox>
的SizeConverter將返回基於輸入的計數大小類別的的IValueConverter,轉換方法可以是這樣的:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int count = (int)value;
if (count < 4) return "Large";
if (count < 12) return "Medium";
return "Small";
}
謝謝 - 已將ListBox.ItemTemplate綁定到一個IMultiValueConverter,該IMultiValueConverter接受可用的大小和項目數並返回相應的資源。 – escouser 2010-08-26 11:57:11