WPF 缩放文本以仅在太大时适合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18069456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:22:20  来源:igfitidea点击:

WPF scale text to fit only when too big

c#wpfscaletruncate

提问by Robert Petz

I am trying to setup a list of items in WPF which contains strings of random length (people's names). The majority of them are generally within a certain size, but occasionally you come across a string so long that it runs out of the bounds of it's container. I've normally just truncated it when it's too long, but I would much rather show the entirety of the string.

我正在尝试在 WPF 中设置一个包含随机长度字符串(人名)的项目列表。它们中的大多数通常都在一定的大小内,但偶尔您会遇到一个字符串太长以至于它超出了它的容器的边界。我通常只是在它太长时截断它,但我更愿意显示整个字符串。

How can I force the text to remain it's normal size, unless too big to fit...in which case scale it down to fit?

我怎样才能强制文本保持其正常大小,除非太大而不适合......在这种情况下将其缩小以适合?

NOTE: This is not the same as scaling all text to fit a certain size, which is accomplished using a viewbox around the text

注意:这与缩放所有文本以适应特定大小不同,这是使用文本周围的视图框完成的

IE: This is NOT what I want:

IE:这不是我想要的:

<Viewbox MaxWidth="100">
    <TextBlock Text="{Binding EmployeeDisplayName, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Viewbox>

This makes everything scale up when too small, as well as scale down when too big. I ONLY want it to scale down when too big and NEVER scale up when too small...

这使得所有东西在太小时都会放大,而在太大时会缩小。我只希望它在太大时按比例缩小,而在太小时时从不放大...

Any thoughts?

有什么想法吗?

回答by keyboardP

Use a Viewboxbut set its StretchDirectionproperty to DownOnly.

使用 aViewbox但将其StretchDirection属性设置为DownOnly

<Viewbox MaxWidth="100" StretchDirection="DownOnly">
    <TextBlock Text="{Binding EmployeeDisplayName, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Viewbox>