2013-01-22 61 views
2

我在StackPanel內部有一個文本框,並且TextBox設置爲AcceptsReturn,所以當您按Enter/Return鍵時,文本框的高度會變大。垂直調整StackPanel大小以適合其內容

我遇到的問題是,我不知道如何使周圍的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> 
+0

嘗試刪除'Margin'屬性,並在堆棧面板上設置'Height = Auto' –

+0

@ sa_ddam213我需要那裏的邊距,但我仍然拿出它並設置Height =「Auto」,但它沒有有什麼區別。 – Tommy

+0

不是堆棧面板是問題 –

回答

1

根據您的示例,您沒有設置GridView.ItemsPanelGridView.ItemsPanel的默認值是<WrapGrid />,它具有無法更改的設置單元大小。您可能想要更新到<VariableSizedWrapGrid />,但該控件不能更改範圍值,除非在渲染過程中。如果你想要的甚至是可能的,那就需要你使用<StackPanel/>作爲你的GridView.ItemsPanel。但是,<StackPanel/>不會自然包裝,因此您需要找到其他人制作的包裝版本,製作自己的包裝版本,或者將其與單個行或列中的版本一起使用。

某些開發人員嘗試根據他們的<TextBlock />的高度更改其模板的大小。這是一個好主意,但卻是一項難以執行的技術。事實證明,UI元素的大小在渲染之前不會被確定,因此您必須先渲染它,然後爲時已晚。如果你想看看一個開發者是如何完成這個計算的(考慮font-family和font-size和margin等的難點),看看here。這樣的計算將允許您使用<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); 
} 

祝你好運。

+0

非常感謝@Jerry! – Tommy

相關問題