我有一个动态尺寸的Grid
。在内部,我想绘制一个对角线TextBlock
。我已经有一个对角线Path
,您可以在其中设置LineGeometry
进行动态调整。但我在TextBlock
中找不到吊坠。我想念什么吗?
<Grid>
<TextBlock Text="Draft" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="180" FontWeight="Bold" Foreground="#FFA43A3A" RenderTransformOrigin="0.5,0.5"/>
<Path Grid.Row="2" Grid.Column="0" Stroke="Red" StrokeThickness="2" Stretch="Fill">
<Path.Data>
<LineGeometry StartPoint="1,0" EndPoint="0,1" />
</Path.Data>
</Path>
</Grid>
这是我想在不设置绝对RotateTransform
的情况下得到的。
red
的前景是 FrankM 解决方案,green
的前景是 Henrik Hansen
答案 0 :(得分:7)
每当网格大小改变时,您都必须计算TextBlock的角度,例如使用转换器。
这里是一个例子:
<Window x:Class="WpfApplication13.MainWindow"
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"
xmlns:local="clr-namespace:WpfApplication13"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:AngleConverter x:Key="AngleConverter"/>
</Window.Resources>
<Grid x:Name="grid">
<TextBlock Text="Draft" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="120" FontWeight="Bold" Foreground="#FFA43A3A"
RenderTransformOrigin="0.5,0.5">
<TextBlock.RenderTransform>
<MultiBinding Converter="{StaticResource AngleConverter}">
<MultiBinding.Bindings>
<Binding ElementName="grid" Path="ActualWidth"/>
<Binding ElementName="grid" Path="ActualHeight"/>
</MultiBinding.Bindings>
</MultiBinding>
</TextBlock.RenderTransform>
</TextBlock>
<Path Stroke="Red" StrokeThickness="2" Stretch="Fill">
<Path.Data>
<LineGeometry StartPoint="1,0" EndPoint="0,1" />
</Path.Data>
</Path>
</Grid>
</Window>
转换器代码:
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
namespace WpfApplication13
{
public class AngleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double width = values[0] as double? ?? 0;
double height = values[1] as double? ?? 0;
double angleRadians = Math.Atan2(height, width);
return new RotateTransform {Angle = - angleRadians * 180.0 / Math.PI};
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
结果:
答案 1 :(得分:1)
您还可以将TextBlock包装在ViewBox中。也会缩放文本,但这可能是不希望的吗?:
<Viewbox Stretch="Fill" StretchDirection="Both">
<TextBlock Text="Draft" FontWeight="Bold" Foreground="#FFA43A3A" Margin="5" RenderTransformOrigin="0.5,0.5" >
<TextBlock.RenderTransform>
<RotateTransform Angle="-35.0" />
</TextBlock.RenderTransform>
</TextBlock>
</Viewbox>