我正在尝试使垂直拉伸(stretch)在 WPF 中按预期工作,但由于某种原因,它只占用了它需要的空间,而不是可用的空间。
首先,我将 WPF 与 C# 和 Prism 一起使用。
在 Shell.xaml(应用程序的主要 xaml)中,我有一个包含 2 列和 1 行的网格。这个想法是有一个侧面板和一个主应用程序区域。主应用程序区域网格设置为自动宽度和自动高度。这按预期工作,它确实可以缩放以适应整个应用程序的高度和宽度。
然后我使用 prism 将 View (作为 UserControl 组件)插入主应用程序区域。 UserControl 也设置为 Auto Width 和 Height,通过查看 Expression Blend 中的默认设置,HorizontalAlignment 和 VerticalAlignment 设置为拉伸(stretch)!
但是,加载的 Prism UserControl 仅在 Width 上延伸,而不在高度上!通过为其提供视觉反馈的背景颜色,我可以看到它只根据需要占用垂直空间,而不是整个可用区域!
这可能是什么解决方案?我已经尝试通过所有设置手动将它们覆盖为宽度和高度自动,水平和垂直对齐以拉伸(stretch),但似乎没有按预期工作!
一些代码:
(Shell.xaml)
<Window Height="1140" Width="1450">
<Grid Margin="0" Background="White">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Background="#FFEEEEEE" Grid.Column="0" Grid.Row="0">
</Grid>
<ItemsControl Width="Auto" Height="Auto" Grid.Row="0" Grid.Column="1" Name="MainRegion" cal:RegionManager.RegionName="MainRegion" Padding="10" Margin="10, 0, 0, 0" Background="#FFFFFFD5" />
</Grid>
</Grid>
</Window>
(应该继承父高度的 View ):
<UserControl Width="Auto" Height="Auto" Background="Red" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<!-- I want this to take the full width and height of the parent -->
</UserControl>
那么这是将 View 加载到主 xaml 中的方式的限制,还是 UserControl 限制,或者其他我不明白的东西?
只是为了澄清;我确实看到在 Shell.xaml 中定义的 ItemsControl 的背景颜色拉伸(stretch)水平和垂直,但没有看到加载到 ItemsControl 中的 View 的背景。
请注意,我删除了一些 xaml 以使这一点更容易理解!
谢谢!
最佳答案
ItemsControl.ItemsPanelTemplate
的默认值是 StackPanel
,它垂直压缩其所有子项,给出您描述的症状。
解决方案 code-zoop 将此更改为 <Grid>
.只要该区域只能有一个 View ,这将很有效。但是,如果该区域有多个 View ,则它们将全部叠放,而不是并排放置。
如果您想要一个可以处理多个 View 但允许 View 拉伸(stretch)到该区域的完整大小的区域,请使用 DockPanel
反而:
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<DockPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
这会将第一个 View 放在左侧的面板中,下一个放在它旁边,依此类推,直到最后一个 View 将填充所有剩余空间。
如果您喜欢像 StackPanel 那样让多个 View 垂直堆叠,则必须在 ItemContainerStyle 中进行设置:
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<DockPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="DockPanel.Dock" Value="Top" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
关于WPF,让垂直拉伸(stretch)按预期工作!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1700701/