2013-02-22 27 views
1

我有一個TextBlock,它周圍有一個Border,它位於Canvas的內部,我用它將它作爲自定義控件的一部分進行動畫處理。該塊從屏幕底部滑過圖像頂部。我試圖用的ActualHeight來確定將它移動到頁面上的距離有多遠,但是當文本太多以至於它包裝成兩行時,ActualHeight返回的大小與有單行的大小相同。當TextBlock中的文字換行時,ActualHeight不正確

的TextBlock:

<DataTemplate DataType="{x:Type contentTypes:BusinessAdText}" x:Key="BusinessAdTextTemplate"> 
    <Border Background="#a9a9a975" 
     Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Canvas}}, Path=ActualWidth}"> 
     <TextBlock Margin="20" Text="{Binding Text}" 
      TextWrapping="Wrap"> 
     </TextBlock> 
     </Border> 
</DataTemplate> 

這種風格應用了具有畫布:

<Style TargetType="local:BusinessAd"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="local:BusinessAd"> 
       <Border Background="Transparent"> 

        <Canvas ClipToBounds="True"> 
         <ContentPresenter x:Name="PART_Content"             
              VerticalAlignment="Center" 
              HorizontalAlignment="Center" /> 
        </Canvas> 

       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

代碼背後BusinessAd.cs有:

public override void OnApplyTemplate() 
{ 
    base.OnApplyTemplate(); 
    _contentPart = GetTemplateChild("PART_Content") as FrameworkElement;       
} 

然後,只需使用簡單的DoubleAnimation是我將它移動到屏幕上:

if (_contentPart != null && _isLoaded) 
{ 
    _storyboard.Stop(); 

    vAnimation.From = ActualHeight; 
    vAnimation.To = ActualHeight - _contentPart.ActualHeight; 
    //_contentPart.ActualHeight returns 46.something no matter how much text is there 

    vAnimation.Duration = new Duration(TimeSpan.FromSeconds(Duration)); 

    if (_storyboard.Children.Count == 0) 
    { 
     _storyboard.Children.Add(vAnimation); 

     Storyboard.SetTargetProperty(vAnimation, new PropertyPath("(Canvas.Top)")); 
     Storyboard.SetTarget(vAnimation, _contentPart);               
    } 

    _storyboard.Begin(); 
} 

回答

2

你必須檢查ActualHeight之前調用UpdateLayout()

if (_contentPart != null && _isLoaded) 
{ 
    _storyboard.Stop(); 
    UpdateLayout(); 

    vAnimation.From = ActualHeight; 
    vAnimation.To = ActualHeight - _contentPart.ActualHeight; 
    //_contentPart.ActualHeight returns 46.something no matter how much text is there 

    vAnimation.Duration = new Duration(TimeSpan.FromSeconds(Duration)); 

    if (_storyboard.Children.Count == 0) 
    { 
     _storyboard.Children.Add(vAnimation); 

     Storyboard.SetTargetProperty(vAnimation, new PropertyPath("(Canvas.Top)")); 
     Storyboard.SetTarget(vAnimation, _contentPart);               
    } 

    _storyboard.Begin(); 
} 
+0

感謝您的迴應,但我最終以完全不同的方式討論了這個問題。我在內存中創建了一個TextBlock,然後測量它來獲得高度。 – 2013-05-30 02:59:39

0

我不知道這是否適用於你,但對我來說,在Windows.UI.Xaml.Controls需要的文本塊被前面有這樣的:

myTextBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); 

之前,當我剛纔myTextBlock.Measure(new Size());,它工作時沒有任何文字環繞,但與包裝ActualWidthActualHeight返回該維度根據WrapWholeWords或Wrap