WPF:我可以在应用转换后获取 UIElement 的大小吗? [英] WPF: Can I get the size of a UIElement AFTER a transform is applied?
问题描述
在 WPF/Silverlight 中,我可以在应用转换后获取 UIElement
的计算值吗?
In WPF/Silverlight, can I get the calculated value of a UIElement
after a transformation is applied?
(根据下面的评论):
我有一个堆栈面板,并且我已经对其应用了 TranformGroup
.该组中有两个平移和一个缩放变换.
I've got a stack panel and I've applied a TranformGroup
to it. There are two translate and one scale transforms in this group.
(警告,前面有伪代码)
(warning, psuedo code ahead)
groupTransform.children.add(new TranslateTransform());
groupTransform.children.add(new ScaleTransform());
groupTransform.children.add(new TranslateTransform());
containerToScale.RenderTransform = groupTransform;
...
// code that sets values to all the transforms
显然,比例变换是我最感兴趣的.
Obviously the scale transform is the one I'm most interested in.
推荐答案
Matthew,正如您所指出的,ActualWidth
和 ActualHeight
在应用转换时不会改变.ActualWidth
和 ActualHeight
表示布局系统完成控件大小计算后的宽度/高度(基于Margin
等值,HorizontalAlignment
等)
Matthew, as you pointed out ActualWidth
and ActualHeight
don't change if you apply transforms. ActualWidth
and ActualHeight
represent the calculated width/height after the layout system has finished calculating the size of a control (based on values such as Margin
, HorizontalAlignment
, etc.)
考虑所有已应用于控件的缩放变换来获取控件大小的一种方法是向上走可视化树并将所有缩放变换应用于 ActualWidth
和 <控件的代码>实际高度:
One way to get the size of a control taking into account all of the scale transformations that have been applied to it is to walk up the visual tree and apply all scale transforms to the ActualWidth
and ActualHeight
of a control:
public static Size GetActualSize(FrameworkElement control)
{
Size startSize = new Size(control.ActualWidth, control.ActualHeight);
// go up parent tree until reaching root
var parent = LogicalTreeHelper.GetParent(control);
while(parent != null && parent as FrameworkElement != null && parent.GetType() != typeof(Window))
{
// try to find a scale transform
FrameworkElement fp = parent as FrameworkElement;
ScaleTransform scale = FindScaleTransform(fp.RenderTransform);
if(scale != null)
{
startSize.Width *= scale.ScaleX;
startSize.Height *= scale.ScaleY;
}
parent = LogicalTreeHelper.GetParent(parent);
}
// return new size
return startSize;
}
public static ScaleTransform FindScaleTransform(Transform hayStack)
{
if(hayStack is ScaleTransform)
{
return (ScaleTransform) hayStack;
}
if(hayStack is TransformGroup)
{
TransformGroup group = hayStack as TransformGroup;
foreach (var child in group.Children)
{
if(child is ScaleTransform)
{
return (ScaleTransform) child;
}
}
}
return null;
}
请记住,如果您的视觉树很深或者您多次执行此操作,这可能效率低下.然而,在实践中,我从未遇到过任何问题.
Keep in mind that this might be inefficient if your visual tree is deep or you perform this many times. In practice I've never run into any problems with this, however.
这篇关于WPF:我可以在应用转换后获取 UIElement 的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!