c# - 如何调整 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;
}
解决方案
如果您希望每个项目成为网格的高度,这与标记中的列表框相同。您可以绑定到实际高度。
<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>
我把它作为一个窗口的内容,当网格填充它时它会响应窗口大小的变化
推荐阅读
- java - 如何将xml转换为java字符串列表
- wpf - 与 WPF StackPanel 相比,使用 WPF DevExpress LayoutControl 有哪些优势?
- jms - ActiveMQ - 长时间运行后,代理接受消息但不排队
- javascript - ArcGIS 突出显示图形
- ruby-on-rails - 在 where 子句中对同一模型具有多个嵌套关系的 ActiveRecord 查询
- reactjs - 如何在 React Chart.js 2 上自定义边框样式
- angular - 为什么 IIS 托管 Angular 8 应用程序提供奇怪的 JavaScript 内容?
- android - 如何将 API 中的数据分配给 Android 中的全局变量?
- spring - 每天创建新的 Spring 日志文件
- reactjs - 在移动设备上查看 React 应用程序时遇到问题