簡體   English   中英

垂直調整StackPanel的大小以適合其內容

[英]Vertically resize StackPanel to fit around its contents

我在StackPanel有一個文本框,並且TextBox設置為AcceptsReturn ,所以當您按Enter / Return鍵時,文本框的高度會變大。

我遇到的問題是我不知道如何使周圍的StackPanel以及文本框的高度發生變化。 因此,當文本框更改時, StackPanel應更改。

我們應該怎么做?

    <GridView x:Name="texties" Grid.Row="1" Margin="120, 0, 0, 0" ItemsSource="{Binding Something, Mode=TwoWay}" SelectionMode="Multiple">
        <GridView.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="10" Orientation="Vertical" Width="210" >
                    <StackPanel.ChildrenTransitions>
                        <TransitionCollection>
                            <AddDeleteThemeTransition/>
                        </TransitionCollection>
                    </StackPanel.ChildrenTransitions>
                    <TextBlock Text="{Binding Name, Mode=TwoWay}" FontWeight="Bold" Style="{StaticResource ItemTextStyle}" />
                    <TextBox Text="{Binding Content, Mode=TwoWay}" FontSize="12" Background="{x:Null}" BorderBrush="{x:Null}" BorderThickness="0, 0, 0, 0" AcceptsReturn="True" IsSpellCheckEnabled="True" />
                </StackPanel>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

根據您的示例,您沒有設置GridView.ItemsPanel GridView.ItemsPanel的默認值為<WrapGrid /> ,其設置的單元格大小無法更改。 您可能會想更新到<VariableSizedWrapGrid />但是此控件無法更改跨度值,除非在渲染期間。 如果您想要的甚至是可能的,則要求您使用<StackPanel/>作為GridView.ItemsPanel 但是, <StackPanel/>並不是本機包裝的,因此您將需要找到其他人制作的包裝版本,自己制作包裝版本或將其放在一行或一列中。

一些開發人員嘗試根據其<TextBlock />的高度來更改模板的大小。 這是一個好主意,但執行起來卻很困難。 事實證明,UI元素的大小直到渲染后才確定,因此您必須先渲染它,然后為時已晚。 如果您想了解一位開發人員是如何完成此計算的(請考慮字體家族的難度以及字體大小和邊距等),請參見此處 這樣的計算將允許您使用<VariableSizedWrapGrid />

在此示例中,他正在計算一個橢圓,但這是相同的計算。

protected override Size MeasureOverride(Size availableSize)
{
    // just to make the code easier to read
    bool wrapping = this.TextWrapping == TextWrapping.Wrap;


    Size unboundSize = wrapping ? new Size(availableSize.Width, double.PositiveInfinity) : new Size(double.PositiveInfinity, availableSize.Height);
    string reducedText = this.Text;


    // set the text and measure it to see if it fits without alteration
    if (string.IsNullOrEmpty(reducedText)) reducedText = string.Empty;
    this.textBlock.Text = reducedText;
    Size textSize = base.MeasureOverride(unboundSize);


    while (wrapping ? textSize.Height > availableSize.Height : textSize.Width > availableSize.Width)
    {
        int prevLength = reducedText.Length;

        if (reducedText.Length > 0)
            reducedText = this.ReduceText(reducedText);    

        if (reducedText.Length == prevLength)
            break;

        this.textBlock.Text = reducedText + "...";
        textSize = base.MeasureOverride(unboundSize);
    }

    return base.MeasureOverride(availableSize);
}

祝你好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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