[英]WPF UserControl fill mainwindow
我在使UserControl正確填充父窗口/調整父窗口大小時遇到麻煩。 我正在使用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>
這是我在MainWindow中啟動UserControl時的顯示效果
是否可以在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中包含很多項目的情況下,窗口不會變得太大。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.