![](/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.