簡體   English   中英

使 WPF TextBlock 只增長而不縮小?

[英]Making a WPF TextBlock be only grow and not shrink?

在我的應用程序中,我多次設置名為tbkStatusTextBlockText

如何讓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也會增長。 因此,控制不能收縮。

我想你可以只聽像SizeChangedLayoutUpdated這樣的布局事件或編寫某種行為

在下面的示例中,基本前提是偵聽這些事件中的任何一個,並強制您的控制權永不收縮

請注意,這完全未經測試,只是一個想法,也許您可​​以改為設置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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM