【发布时间】:2015-02-21 15:40:47
【问题描述】:
我想在带有 TextTrimming 的 ViewboxPanel 控件中拥有一个 TextBlock,但为了做到这一点,TextBlock 必须有一个宽度。但是为什么在ViewboxPanel中宽度与显示的宽度无关?
<Window x:Class="SizeTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:SizeTest.Utils.Converters;assembly=SizeTest.Utils"
xmlns:controls="clr-namespace:SizeTest.Utils.Controls;assembly=SizeTest.Utils"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<converters:MarginConverter x:Key="MarginConverter"/>
</ResourceDictionary>
</Window.Resources>
<Grid>
<controls:ViewboxPanel HorizontalAlignment="Left">
<controls:ViewboxPanel.Margin>
<MultiBinding Converter="{StaticResource MarginConverter}" ConverterParameter="0;40;0;40">
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}" Path="ActualHeight" />
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}" Path="ActualWidth" />
</MultiBinding>
</controls:ViewboxPanel.Margin>
<TextBlock Text="fgghgfhdfgfgsdfdsfdsfdsfsdf" Width="130" TextTrimming="CharacterEllipsis" />
</controls:ViewboxPanel>
</Grid>
</Window>
控制:
public class ViewboxPanel : Panel
{
private double scale;
protected override Size MeasureOverride(Size availableSize)
{
double height = 0;
Size unlimitedSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
foreach (UIElement child in Children)
{
child.Measure(unlimitedSize);
height += child.DesiredSize.Height;
}
scale = availableSize.Height / height;
return availableSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
Transform scaleTransform = new ScaleTransform(scale, scale);
double height = 0;
foreach (UIElement child in Children)
{
child.RenderTransform = scaleTransform;
child.Arrange(new Rect(new Point(0, scale * height), new Size(finalSize.Width / scale, child.DesiredSize.Height)));
height += child.DesiredSize.Height;
}
return finalSize;
}
}
ViewboxPanel 由边距和百分比控制。但是为什么 TextBlock 的 130 的宽度与 ViewboxPanel 的 525 的宽度匹配(按窗口宽度)?
我希望能够调整窗口大小,并且文本块的宽度应该跟随,以便通过修剪来显示/隐藏文本。所以文本块的宽度应该绑定到它所在的网格的宽度,像这样:
Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}, Path=ActualWidth}"
但我不明白为什么 525 不正确!?
【问题讨论】:
-
ViewBox 的用途是什么?你可以用一些面板替换它,还是直接在网格下添加文本块?
-
目的是控制文字的大小。在我的最终应用中,视图框是通过其边距控制并按百分比设置的。
-
ViewBox 肯定不是你需要的。考虑改用一些面板或边框。
-
其实我现在正在使用这个例子,因为它解决了另一个问题。这是基于面板的,但有同样的问题。 stackoverflow.com/questions/4542835/…
-
我更新了描述宽度,让我的应用更真实地使用。