0

我有以下代码:

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。

我究竟做错了什么?

4

1 回答 1

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));

测量并安排哪些因素会强制重新计算视图中对象的尺寸。

于 2015-07-16T10:54:37.673 回答