首页 > 解决方案 > WPF ItemTemplate 导致列表框内容大小问题

问题描述

在 WPF 项目中,ListBox如果我在 XAML 中手动插入项目,则可以正确呈现,例如:

<ListBoxItem>
    <Grid Background="#7F271043" Width="200" Height="200">
        <Grid.RowDefinitions>
            <RowDefinition Height="110" />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>

        <Image Grid.Row="0" Source="Logo-40p.png" HorizontalAlignment="Center" Margin="10,10,10,10" />
        <TextBlock Grid.Row="1" Text="Test Item" Foreground="White" Margin="10,0,10,0" FontSize="16" VerticalAlignment="Center" />
        <local:Rating Grid.Row="2" HorizontalAlignment="Left" Height="24" Margin="10,0,0,0" VerticalAlignment="Center" Width="130" SelectedValue="4" IsReadOnly="True" />
        <TextBlock Grid.Row="2" Text="Free" Foreground="#FF969292" Margin="0,0,10,0" FontSize="14" HorizontalAlignment="Right" VerticalAlignment="Center" />
    </Grid>
</ListBoxItem>

底部ListBoxItem看起来像:

手动项目插入

但是,我换掉的那一刻<ListBoxItem>

<ListBox.ItemTemplate>
    <DataTemplate>

即使我保持其他所有内容相同,它也会在我的评级控件中产生一个我无法修复的尺寸问题(不响应手动尺寸或拉伸设置):

项目模板

关于如何解决这个问题的任何想法?做ItemTemplate/DataTemplate做一些可能导致控件不遵守手动设置或由它所在的网格行设置的大小的事情?

标签: c#wpfsizedatatemplateitemtemplate

解决方案


设法解决了这个问题 - XAML 中手动定义的行为似乎与/ListBoxItem的输出不同。ItemTemplateDataTemplate

我的评级用户控件有一个指定的高度和宽度,这些高度和宽度被 a 内的实现 XAML(高度/宽度/拉伸)覆盖,ListBoxItem但不在ItemTemplate/内DataTemplate

mc:Ignorable="d" Height="750" Width="4070" MouseLeave="UserControl_MouseLeave">

所以我改为Height/Width改为DesignHeight/DesignWidth来解决这个问题:

mc:Ignorable="d" d:DesignHeight="750" d:DesignWidth="4070" MouseLeave="UserControl_MouseLeave">

推荐阅读