我有一个应用程序,我在其中动态地将各种实例添加到画布中,并且底层画布具有缩放LayoutTransform。这对于像矩形这样的视觉效果非常好,因为它们正确地保持了固定的笔划宽度,但在画布使用LayoutTransform“缩放”时会在形状宽度/高度上进行扩展。但是,对于TextBlock实例,布局转换实际上是缩放文本的呈现,从而使字体实际上变大。我希望发生的是TextBlock的左上角原点与布局转换一起平移,而文本保持相同的大小。
下面是创建画布的ItemsControl的XAML:
<ItemsControl ItemsSource="{Binding Annotations}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding StartX}"/>
<Setter Property="Canvas.Top" Value="{Binding StartY}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.LayoutTransform>
<TransformGroup>
<ScaleTransform ScaleX="{Binding ZoomScale}" ScaleY="{Binding ZoomScale}"
CenterX="0.5" CenterY="0.5"/>
</TransformGroup>
</ItemsControl.LayoutTransform>
</ItemsControl>以下是一些用于呈现绑定集合中的注释的数据模板:
<DataTemplate DataType="{x:Type Annotations:RectangleAnnotation}">
<Rectangle Width="{Binding Width}" Height="{Binding Height}" Stroke="Blue" IsHitTestVisible="False"/>
</DataTemplate>
<DataTemplate DataType="{x:Type Annotations:TextAnnotation}">
<TextBlock Text="{Binding Text}" Foreground="Orange" IsHitTestVisible="False"/>
</DataTemplate>注释实例本身是具有相关绑定属性(StartX、StartY和TextAnnotation的文本)的简单INotifyPropertyChanged实现。
我还没有找到任何简单的方法来防止文本的布局缩放。然而,在我开始寻找解决方案之前,我想我应该检查一下:有谁知道一个干净的方法来解决这个问题?
发布于 2012-08-25 15:40:43
每个变换都有一个反转属性,该属性会撤消其效果。因此,您可以将TextBlock的RenderTransform绑定到缩放画布的转换的反转,这应该会取消其对文本呈现的影响。
左上角通常是缩放的原点,因此如果默认设置为all,则文本应按照您的指定移动到左上角。然而,如果你在画布上使用组合变换或不同的缩放中心,你可能不得不玩弄一些参数,但这应该很容易,例如,编写一个转换器,它只接受变换的比例因子,以便在不移动缩放中心的情况下创建反比例变换。
发布于 2012-08-26 22:41:48
我不能像@hbarck建议的那样绑定到反向,因为这是一个GeneralTransform而不是一个转换。我通过使用元素名绑定到ScaleTransform并使用值转换器来反转缩放,从而解决了这个问题:
<Controls:InvertConverter x:Key="Invert"/>
<DataTemplate DataType="{x:Type Annotations:TextAnnotation}">
<TextBlock Text="{Binding Text}" Foreground="Orange" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<ScaleTransform ScaleX="{Binding ScaleX, ElementName=AnnotationScale, Converter={StaticResource Invert}}"
ScaleY="{Binding ScaleY, ElementName=AnnotationScale, Converter={StaticResource Invert}}"/>
</TextBlock.RenderTransform>
</TextBlock>
</DataTemplate>和下面的转换器代码:
public sealed class InvertConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.GetType() != typeof(double) || targetType != typeof(double))
return null;
return 1/(double)value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.GetType() != typeof(double) || targetType != typeof(double))
return null;
return 1 / (double)value;
}
}https://stackoverflow.com/questions/12117743
复制相似问题