我如何优先考虑WPF文本框包装自动调整大小?

Dav*_*mer 11 c# wpf textbox autosize

我有很多情况下我有自动调整大小的面板或网格,但是如果它们包含一个TextBoxwith TextWrapping="Wrap",TextBox则会在它真正需要之前将面板/网格继续向右扩展,例如下面的图像:

文本框扩展面板

我想要做的是TextBox通过在尝试向右扩展之前包装文本来填充其区域.该问题的简化示例是:

<Grid>
    <Grid Background="Black" />
    <Grid VerticalAlignment="Top" HorizontalAlignment="Left" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBox TextWrapping="Wrap" Height="120" MinWidth="200" />
    </Grid>
</Grid>
Run Code Online (Sandbox Code Playgroud)

我在这里找到了类似的问题,但是发布的最佳解决方案不允许TextBox扩展.该解决方案类似于:

<Grid>
    <Grid Background="Black">
    </Grid>
    <Grid VerticalAlignment="Top" HorizontalAlignment="Left" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Border BorderThickness="0" x:Name="border" Margin="0.5" />
        <TextBox TextWrapping="Wrap" Height="120" MinWidth="200" Width="{Binding ActualWidth, ElementName=border}" />
    </Grid>
</Grid>
Run Code Online (Sandbox Code Playgroud)

除了TextBox使用修改过的行为进行扩展之外 谢谢!

bra*_*ing 8

有一个简单的技巧让它工作.使用帆布,然后将绑定宽度文本框的给ActualWidth的画布和高度画布到的ActualHeight文本框的.

<Canvas 
    x:Name="Canvas" 
    Height="{Binding ElementName=TextBlock, Path=ActualHeight}" 
    VerticalAlignment="Stretch" HorizontalAlignment="Stretch">

        <TextBlock
            x:Name="TextBlock"
            Width="{Binding ElementName=Canvas, Path=ActualWidth}"
            TextWrapping="WrapWithOverflow"
            Text="blah blah blah blah" />


</Canvas>
Run Code Online (Sandbox Code Playgroud)

使用它的我们的生产应用程序的屏幕截图

在此输入图像描述

并调整大小

在此输入图像描述

诀窍是Canvas继承父容器的宽度和子容器的高度.我正在考虑将模式包装在自定义控件中.


sel*_*dog 3

尽管我不建议这样做,因为我认为这会给用户带来意想不到的行为,但这似乎可以实现您所要求的:

XAML:

<TextBox ... MinHeight="120" Width="200" SizeChanged="TextBox_SizeChanged" />

背后代码:

private void TextBox_SizeChanged(object sender, SizeChangedEventArgs e)
{
    try
    {
        if (e.PreviousSize == Size.Parse("0,0")) return;
        if (e.PreviousSize == e.NewSize) return;

        if (e.HeightChanged)
        {
            ((TextBox)sender).Width = e.PreviousSize.Width + 20;
        }
    }

    finally
    {
        e.Handled = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

有几点需要注意,1)为了使其工作,您必须同时使用 aMinHeightWidth来允许扩展,2)水平扩展 20 只是我用于测试目的的任意值;您需要想出一种更可靠的方法来计算变量扩展值。