在应用转换后,如何确定控件的实际宽度和实际高度?
例如,我认为遵循XAML代码应该显示类似400x400的大小(例如,在图片。红色矩形,宽度为400),但宽度和高度等于200。
我做错了什么?
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="VisualCad.Components.TempVisualTests.MainWindow"
mc:Ignorable="d"
x:Name="MyWin"
Title="MainWindow" WindowState="Maximized" Height="500" Width="500">
<Grid>
<Rectangle Width="400" Height="5" Fill="Red" Margin="0,20,0,0" VerticalAlignment="Top"/>
<Canvas x:Name="MyCanvas" Width="200" Height="200">
<Canvas.RenderTransform>
<ScaleTransform CenterX="100" CenterY="100" ScaleX="2" ScaleY="2" />
</Canvas.RenderTransform>
<StackPanel>
<TextBlock Text="{Binding Path=RenderSize, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Canvas}}, StringFormat='Render size: {0}'}" />
<TextBlock Text="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Canvas}}, StringFormat='ActualWidth: {0}'}" />
<TextBlock Text="{Binding Path=ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Canvas}}, StringFormat='ActualHeight: {0}'}" />
</StackPanel>
</Canvas>
</Grid>
</Window>
答案 0 :(得分:2)
此代码适用于我:
var parent = element.Parent as UIElement;
Point bottomLeft = element.TranslatePoint(new Point(0, 0), parent);
Point topRight = element.TranslatePoint(new Point(element.ActualWidth, element.ActualHeight), parent);
var renderWidth = topRight.X - bottomLeft.X;
var renderHeight = topRight.Y - bottomLeft.Y;
答案 1 :(得分:1)
在应用转换后,如何确定控件的实际宽度和实际高度?
您需要自己计算宽度和高度。它应该是非常简单的:
double width = MyCanvas.ActualWidth;
double height = MyCanvas.ActualHeight;
ScaleTransform st = MyCanvas.RenderTransform as ScaleTransform;
if(st != null)
{
width *= st.ScaleX;
height *= st.ScaleY;
}
没有属性会为您返回此大小。转换不会影响ActualWidth
和ActualHeight
属性。