首页 > 解决方案 > 如何调整 ListBoxItems 的大小以适合容器?

问题描述

我正在尝试设置我的 ListBoxItems 的高度,以便它们占据 Grid 的整个高度(例如,如果我有 5 个项目,则单个项目的高度将是总/5)。为了获得网格的高度,我使用了 Loaded 事件(我的第一个猜测是 SizeChanged,但这个不会触发)。我能够在 MVVM 中获得正确的值并计算一个项目的正确高度。但是,我无法使绑定到 ListBoxItem 工作。当我运行我的应用程序项目时不可见,但是当我尝试通过添加 FallbackValue 在我的程序运行时修改我的绑定时,高度被设置为正确的,之前计算的值。

您知道如何使这种方法发挥作用吗?如果不是,有什么替代方案?

查看.xaml

                <Grid x:Name="ListGrid" >
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Loaded">
                            <i:InvokeCommandAction Command="{Binding IconListSizeChanged}" 
                             CommandParameter="{Binding ElementName=ListGrid, Path=ActualHeight}"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <ListBox VerticalAlignment="Center">
                        <ListBox.ItemContainerStyle>
                            <Style TargetType="{x:Type ListBoxItem}">
                                <Setter Property="Height" Value="{Binding DataContext.IconItemHeight}"/>
                            </Style>
                        </ListBox.ItemContainerStyle>
                        //items here
                    </ListBox>
                </Grid>

视图模型.cs

 public ICommand IconListSizeChanged { get; private set; }
 private double iconListHeight;
 public double IconItemHeight => iconListHeight / 1234;

 public ViewModel()
 {
    IconListSizeChanged = new DelegateCommand(param => HandleListHeightChange(param));
    iconListHeight = 30.0 // initial
 }

 private void HandleListHeightChange(object param)
 {
    iconListHeight = (double)param;
 }

标签: c#wpfxaml

解决方案


如果您希望每个项目成为网格的高度,这与标记中的列表框相同。您可以绑定到实际高度。

<Grid>
    <ListBox Name="lb">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Height" Value="{Binding ActualHeight, ElementName=lb}"/>
                <Setter Property="VerticalContentAlignment" Value="Stretch"/>
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            </Style>
        </ListBox.ItemContainerStyle>
        <Rectangle Fill="Blue"/>
        <Rectangle Fill="Yellow"/>
        <Rectangle Fill="Red"/>
    </ListBox>
</Grid>

我把它作为一个窗口的内容,当网格填充它时它会响应窗口大小的变化


推荐阅读