Silverlight - 获取设置为拉伸/自动的控件的尺寸



我有一个在我的xaml中定义的边框。我需要以编程方式将另一个控件维度设置为与 xaml 中定义的边框相同。

我似乎无法获得尺寸,因为高度和宽度设置为自动,水平对齐和垂直对齐设置为拉伸。

 <Border BorderBrush="Silver" BorderThickness="1" Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Name="borderPlaceHolderIframe" />

我试过了

borderPlaceHolderIframe.Width //(Result= -1.#IND)
borderPlaceHolderIframe.ActualWidth  //(Result= 0.0)
borderPlaceHolderIframe.DesiredSize //(Result= 0.0)
borderPlaceHolderIframe.RenderSize //(Result= 0.0)

我还尝试获取放置边框的layoutRoot网格的尺寸,但是其高度和宽度也是自动的。

有什么方法可以在不定义固定高度和宽度的情况下获取此控件的尺寸?

使用 LayoutUpdated 事件计算所有值。

  void MainPage_LayoutUpdated(object sender, EventArgs e)
    {
    borderPlaceHolderIframe.Width 
    borderPlaceHolderIframe.ActualWidth  
    borderPlaceHolderIframe.DesiredSize 
    borderPlaceHolderIframe.RenderSize
    }

事实证明,维度获取/设置框架元素的维度。无法保证何时计算这些值。

为了解决这个问题,我调用了附加到处理程序的beginInvoke。在这种方法中,我可以访问我需要的值。(您只能单独访问此方法中的值,因此如果您希望在其他地方使用它们,我建议将值存储到全局变量中)

这是我使用的代码 -

//ActualWidth and ActualHeight are calculated values and may not be set yet
//therefore, execute GetLayoutRootActualSize() asynchronously on the thread the  Dispatcher is associated with
Me.Dispatcher.BeginInvoke(AddressOf GetLayoutRootActualSize)
Private Sub GetLayoutRootActualSize()
    Me.tbxInvoke.Text = Me.LayoutRoot.ActualWidth.ToString() & ", " & Me.LayoutRoot.ActualHeight.ToString()
End Sub

作为参考,我相信使用 sizeChanged 事件也可以获得相同的结果,代码是 -

Private Sub LayoutRoot_SizeChanged(ByVal sender As Object, ByVal e As System.Windows.SizeChangedEventArgs) Handles LayoutRoot.SizeChanged
    Me.tbxSizeChanged.Text = Me.LayoutRoot.ActualWidth.ToString() & ", " & Me.LayoutRoot.ActualHeight.ToString()
End Sub

最新更新