我有一个 TextBlock
,周围有一个 Border
,它位于 Canvas
内部,我用它来将其动画化,作为自定义控件。该 block 从屏幕底部滑入图像顶部。我试图使用 TextBlock
的 ActualHeight
来确定将其移动到页面上的距离,但是当文本太多时,它会换行为两行, ActualHeight
返回与单行相同的大小。
文本 block :
<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>
应用此样式时具有 Canvas :
<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();
}
最佳答案
在检查 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();
}
关于wpf - 当文本在 TextBlock 内换行时,ActualHeight 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15028455/