![](/img/trans.png)
[英]How to grow/shrink a TextBlock (Font Size) to the available space in WPF?
[英]Making a WPF TextBlock be only grow and not shrink?
在我的应用程序中,我多次设置名为tbkStatus
的TextBlock
的Text
。
如何让TextBlock
自动增长以适应文本但在文本更改时不缩小?
StatusText
每隔几秒就会改变一次,有长文本和短文本的状态。 我希望我的 TextBlock 适合最长文本的大小,即使有短文本,TextBlock 也不应该缩小
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="200" Width="400"
WindowStartupLocation="CenterScreen"
ResizeMode="CanMinimize" Topmost="True">
<Window.Resources>
</Window.Resources>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="AUTO" />
<RowDefinition Height="AUTO" />
<RowDefinition Height="AUTO" />
<RowDefinition Height="AUTO" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Please wait ..." Grid.Row="1" Margin="6"/>
<TextBlock Name="tbkStatus" Grid.Row="2" Margin="6" TextWrapping="Wrap" Text="{Binding StatusText}"/>
<ProgressBar Grid.Row="3" Margin="6" Height="20"/>
<Button Grid.Row="4" HorizontalAlignment="Center" Padding="24,3" Margin="6" Content="Stop"/>
</Grid>
</Window>
Xaml 唯一解决方案:
<TextBlock Text="{Binding StatusText}"
MinWidth="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth}"
HorizontalAlignment="Left"/>
这样,每当Width
增长时, MinWidth
也会增长。 因此,控制不能收缩。
我想你可以只听像SizeChanged
或LayoutUpdated
这样的布局事件或编写某种行为
在下面的示例中,基本前提是侦听这些事件中的任何一个,并强制您的控制权永不收缩
请注意,这完全未经测试,只是一个想法,也许您可以改为设置
MinWidth
属性
xml
<TextBlock x:Name="tbkStatus" SizeChanged="OnSizeChanged"/>
背后的代码
private double _lastSize;
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
var textBlock = sender as TextBlock;
if (textBlock == null)
{
return;
}
if (e.WidthChanged)
{
if (textBlock.Width < _lastSize)
{
textBlock.Width = _lastSize;
}
_lastSize = textBlock.Width;
}
}
另请注意
SizeChangedEventArgs
类具有许多您可以利用的属性
你可以这样做:
<TextBlock Name="tbkStatus" Grid.Row="2" Margin="6" TextWrapping="Wrap" Text="{Binding StatusText}"/>
由于TextBlock
没有TextChange
事件,这将完成这项工作
DependencyPropertyDescriptor dp = DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock));
int textLength =0
dp.AddValueChanged(tbkStatus, (object a, EventArgs b) =>
{
if (textLength < tbkStatus.Text.Length)
{
textLength = tkbStatus.Text.Length;
tbkStatus.Width = textLength * SomeValue; //You have to play around and see what value suits you best since it depends on font and it's size
}
});
或者,您可以使用TextBox
并使其只读并使用TextChanged
事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.