我目前正在制定 WPF 应用程序的布局,并且似乎在我的一个控件的布局中有点障碍。此控件是动态调整大小的,因此它应该适合它所在的视口的大小。我遇到的问题是一个非常直观的问题,所以我会尽力描述它。这是它目前的样子:
替代文字 http://gallery.me.com/theplatz/100006/Capture/web.png?ver=12472534170001
每个“Col N Row X”标题下方的区域是一个 TextBlock,其中将放置不同长度的文本。为了使 TextBlock 真正换行,我在 stackoverflow 上找到了一个解决方案,它说将文本块的宽度绑定到列的宽度。这是 Grid 定义的片段以及第一列的定义:
<!-- Change Detail Contents Grid -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="270" Width="2*" />
<ColumnDefinition MinWidth="160" Width="*" />
<ColumnDefinition MinWidth="160" Width="*" />
<ColumnDefinition MinWidth="160" Width="*" />
</Grid.ColumnDefinitions>
<!--
We bind the width of the textblock to the width of this border to make sure things resize correctly.
It's important that the margin be set to 1 larger than the margin of the textblock or else you'll end
up in an infinate loop
-->
<Border Grid.Column="0" Margin="6" Name="FirstBorder" />
<Border Grid.Column="0" BorderThickness="0,0,1,0" BorderBrush="{DynamicResource ColumnBorderBrush}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<Border Style="{DynamicResource DetailHeadingBorder}">
<TextBlock Text="Col 1 Row 1" Style="{DynamicResource DetailHeadingText}" />
</Border>
<TextBlock Text="{Binding IsReason, ElementName=ChangeDetailRoot}" Style="{DynamicResource DetailText}" Width="{Binding ActualWidth, ElementName=FirstBorder}" />
</StackPanel>
<StackPanel Grid.Row="1">
<Border Style="{DynamicResource DetailHeadingBorder}">
<TextBlock Text="Col 1 Row 2" Style="{DynamicResource DetailHeadingText}" />
</Border>
<TextBlock Text="{Binding WasReason, ElementName=ChangeDetailRoot}" Style="{DynamicResource DetailText}" Width="{Binding ActualWidth, ElementName=FirstBorder}" />
</StackPanel>
</Grid>
</Border>
</Grid>
当窗口/视口宽度增加时,一切都会调整大小。当宽度减小时问题变得明显。如果你突然从最大化到原始大小,所有的列都会“跳舞”回到它们指定的大小。我的意思是您可以看到每列的大小都缩小了,因为它按比例调整回其较小的大小。我发现这是直接由
Width="{Binding ActualWidth, ElementName=FirstBorder}"
在每个 TextBlocks 上。当这些控件同时出现在屏幕上时,问题也会变得明显更糟。但是,如果没有该行,则每个 TextBlock 内的文本将继续向右增长,添加的文本越多,而不是在列中向下换行。
有没有更好的方法来完成我想要完成的事情?使用 HTML/CSS,这将是一件相当简单的事情。我花了几个小时在谷歌上搜索并通过 stackoverflow 寻找这个问题的答案。
我来自 HTML/CSS 的深厚背景,所以如果这不是 WPF 应该擅长的,请告诉我。