我有以下代码:
的Xaml
<GroupBox x:Name="FrameStatusGroupBox" Header="Frame Status" Foreground="DarkRed" Grid.Row="3">
<ItemsControl x:Name="FrameStatusItemsControl" ItemsSource="{Binding KeepFramesSection.FrameStatus, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas x:Name="FrameStatusCanvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="LightGray" Height="Auto" Width="Auto" IsEnabled="{Binding MarkingFileLoaded, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</GroupBox>
视图模型
foreach (var currentCanvas in ListOfCanvases)
{
var widthRatio = FrameStatus.ActualWidth / currentCanvas.ActualWidth;
var heightRatio = FrameStatus.ActualHeight / currentCanvas.ActualHeight;
foreach (var currentBoundingBox in currentCanvas.Children)
{
var savedObj = XamlWriter.Save(currentBoundingBox);
var reader = new StringReader(savedObj);
var xmlReader = XmlReader.Create(reader);
var newChild = (UIElement) XamlReader.Load(xmlReader);
var p = ((UIElement) currentBoundingBox).TransformToAncestor(currentCanvas)
.Transform(new Point(0, 0));
p.X *= widthRatio;
p.Y *= heightRatio;
Canvas.SetLeft(newChild, p.X);
Canvas.SetTop(newChild, p.Y);
FrameStatus.Children.Add(newChild);
}
}
FrameStatus.UpdateLayout();
我正在尝试获取原始Canvas
和新Canvas
的尺寸,因为我想将孩子从一个复制到另一个,并且它们的大小不同。
执行此操作时,由于某种原因,此代码:FrameStatus.ActualWidth
和此代码:FrameStatus.ActualHeight
都返回0。
我做错了什么?
答案 0 :(得分:0)
您是否等到视图已满载?如果您尝试早期访问这些属性,则可能尚未初始化。
另一个答案(Why are ActualWidth and ActualHeight 0.0 in this case?)建议致电
window.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
window.Arrange(new Rect(0, 0, window.DesiredWidth, window.DesiredHeight));
测量和排列会强制重新计算视图中对象的尺寸。