2017-05-24 57 views
0

如何在應用轉換後確定控件的實際寬度和實際高度?如何在應用ScaleTransform後確定控件大小?

例如,我認爲下面的XAML代碼應顯示大小類似400×400(例如,在照片。紅色長方形,其寬度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

這裏有什麼實際的目標是什麼?你需要什麼信息? –

+0

@EdPlunkett在正確的控件安排在我的控制任何轉換後。 – slavka

回答

0

如何確定實際寬度和控制的實際高度,將改造後?

你需要計算的寬度和高度自己。它應該是非常直接,但:

double width = MyCanvas.ActualWidth; 
double height = MyCanvas.ActualHeight; 

ScaleTransform st = MyCanvas.RenderTransform as ScaleTransform; 
if(st != null) 
{ 
    width *= st.ScaleX; 
    height *= st.ScaleY; 
} 

沒有財產,將爲您返回此大小。轉換不影響ActualWidthActualHeight屬性。

+0

在這種情況下 - ScaleTransform就是一個例子,在轉換之後,我們需要一些操作來獲得實際大小的控件。 – slavka

+0

答案仍然相同:您需要計算大小。我給你舉例說明了如何做到這一點,所以我不知道你還有什麼要求。 – mm8

0

此代碼的工作對我來說:

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;