WPF:根据项目的大小和数量使用不同的模板 [英] WPF: Use a different template depending on size and number of items

查看:31
本文介绍了WPF:根据项目的大小和数量使用不同的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何根据项目的大小和数量来更改模板.这与根据大小或 Windows 7 程序缩略图动态变化的功能区非常相似.

I'm trying to work out how I can alter the template depending on the size and number of items. This is very similar to the ribbon which dynamically changes depending on the size, or Windows 7 thumbnail of programs.

在这种情况下,它是一个 ListBox 的 ItemTemplate,我想缩小图像的大小或不显示它,而不是有滚动条.

In this case, it's an ItemTemplate of a ListBox and I want to reduce the size of the image or not display it, rather than having scroll bars.

<ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Title}" />                        
                <Image Source="{Binding ImageUrl}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

谢谢

推荐答案

你可以在 ListBox 上设置一个样式,它会根据项目的数量来切换 ItemTemplate.

You could set a style on the ListBox, which switches ItemTemplate based on the number of items.

<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,它根据传入的计数返回一个大小类别,convert 方法可能是这样的:

The SizeConverter would be an IValueConverter which returns a size category based on the incoming count, the convert method could be something like this:

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

这篇关于WPF:根据项目的大小和数量使用不同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆