我无法让我的用户控件使用父窗口正确填充/调整大小。我正在使用 MVVM 编写一个 WPF 应用程序。我搜索了其他答案,但一直无法弄清楚。
MainWindow.xaml
<Window x:Class="QiXR.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:QiXR.ViewModel"
xmlns:vw="clr-namespace:QiXR.View"
Title="MainWindow">
<Window.Resources>
<DataTemplate DataType="{x:Type vm:XRTestCaseListViewModel}">
<vw:XRTestCaseListView/>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding ViewModels}" />
</Grid>
用户控件
<UserControl x:Class="QiXR.View.XRTestCaseListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
<UserControl.Resources>
<Style x:Key="DataGridCheckBoxStyle" TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</UserControl.Resources>
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
<RowDefinition Height="45"/>
</Grid.RowDefinitions>
这是我启动它时显示器的外观主窗口中的用户控件
是否可以在 UserControl 或 MainWindow 的 xaml 中执行此操作?谢谢
ItemsControl 默认使用StackPanel
来显示数据,StackPanel
将其大小限制为其子级的大小。
ViewModels
集合中只有一个项目,请尝试将ItemsPanelTemplate
切换到类似DockPanel
的东西:
<ItemsControl ItemsSource="{Binding ViewModels}">
<!-- ItemsPanelTemplate -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<DockPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
如果您计划拥有多个项目,则还必须为 DockPanel.Dock="Top"
设置 ItemContainerStyle
属性,也许使用转换器,以便最后一项DockPanel.Dock="Fill"
。或者切换到使用不同的面板类型,该面板类型也可以拉伸以填充所有可用空间,并允许其子面板也可以拉伸。
也就是说,如果您只显示一个项目,我建议切换到使用 ContentControl
而不是 ItemsControl
。
<ContentControl Content="{Binding MyViewModel}" />
如果要使窗口的大小与内容(包括 ItemsControl 下方的菜单和按钮)相同,并可以选择在有更多内容可用时使窗口变大,则可以设置 SizeToContent 属性:
<Window x:Class="Project.Window"
x:Name="userControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" MaxHeight="700"
SizeToContent="Height" WindowStartupLocation="CenterScreen">
</Window>
窗口的高度将增加以适应其内容。在其中,您还可以设置 MaxHeight 属性,以便在 ItemsControl 中包含相当多的项时窗口不会变得太大。