XAML是一个页面,其中包含一个Viewbox内的项目列表。目标是在部门名称下面放置一段注释。我将我的itemscontrol的背景设置为红色,以便更容易地看到它如何填充页面。
<Grid >
<Viewbox x:Name="slideViewBox">
<ItemsControl x:Name="itemsControl" Background="Red" ItemsSource="{Binding JournalEntries}" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="ParentGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" HorizontalAlignment="Left" Foreground="White" Text="{Binding Department}" FontSize="32"/>
<TextBlock x:Name="detailsTextBlock" Grid.Row="1" Foreground="White" Text="{Binding DetailedExplaination}" HorizontalAlignment="Left" TextWrapping="Wrap" FontSize="20" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Viewbox>
</Grid>
生成的结果如下:
![enter image description here](https://istack.dev59.com/m3QXT.webp)
![enter image description here](https://istack.dev59.com/eBKdp.webp)
我在Size_Changed事件处理程序中编写了一些代码,使我更接近我的目标,但还没有完全达到。我手动调整itemscontrol的宽度以强制文本换行。我只需要让它自动完成,这样它看起来就像第二张图片,在页面加载时就能实现。
private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
{
var child = VisualTreeHelper.GetChild(slideViewBox, 0) as ContainerVisual;
var scale = child.Transform as ScaleTransform;
double pageheight = e.NewSize.Height;
double pagewidth = e.NewSize.Width;
double textHeight;
double textWidth;
textHeight = itemsControl.ActualHeight * scale.ScaleY;
textWidth = itemsControl.ActualWidth * scale.ScaleX;
if (textWidth == pagewidth)
{
itemsControl.Width = itemsControl.ActualWidth * .9;
}
else if (textHeight == pageheight)
{
itemsControl.Width = itemsControl.ActualWidth * 1.1;
}
}