我需要在WPF呈現它之前計算可視元素的邏輯寬度。我如何計算WPF視覺元素的邏輯寬度?
爲了便於說明,我會說這個視覺元素可能是一個Polygon對象。它可能是其他的東西,但多邊形可以很容易地形象化。
所以XAML可能看起來是這樣的:
<Window x:Class="MyCLRNamespace.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Window>
和代碼隱藏看起來是這樣的:
namespace MyCLRNamespace
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
//This is the visual element in question. It's a simple triangle.
Polygon MyPolygon = new Polygon();
MyPolygon.Points = new PointCollection { new Point(100, 0),
new Point(200, 200),
new Point(0, 200) };
double PolyWidth = MyPolygon.Width;
/* In this case, PolyWidth will be set to double.NaN, since
MyPolygon.Width is never set.
I need to be able to calculate the logical width of an element,
unrelated to the WPF rendering system. This means that I can't
rely on FrameworkElement.ActualWidth to calculate the width for
me. I need to be able to look at the MyPolygon object (or its
content) and figure out that it is set to a visual element that
should be 200dips wide before any parent element applies any
operations to it - regardless of what MyPolygon.Width may or may
not be set to.
It should also be noted that I don't have to rely on
FrameorkElement. If there are more generic alternatives, such as
the UIElement or Visual classes, I'd prefer to use those instead
of the more specific FrameworkElement. The more robust I can make
this, the better. */
}
}
}
如果在調用度量後得到0,0,則可以將容器元素直接放在可視樹中的元素上方並測量該元素。也許不是最好的解決方案,但是如果你絕望的話,它是有效的。 – 2016-10-06 18:27:25