2013-02-22 53 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