我需要在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