2012-12-13 27 views
2

我有一個WPF應用程序,其佈局由頂層的3行Grid組成。限制WPF中「自動」和「1 *」行的高度

我想讓中間一行用盡它需要的空間(它需要的最大空間是有限的,但取決於窗口的寬度)。 最下一行將用盡剩餘空間。 棘手的部分是第一行。 其大小可以根據切換大部分內容的可見性的按鈕而變化。我希望它能夠使用至多50%的高度,但不會超過它真正需要的。 以下XAML介紹我想要完成的任務:

<Grid.RowDefinitions> 
     <!-- neither "1*" nor "Auto" fully meets my needs --> 
     <RowDefinition Height="Min(1*,Auto)"></RowDefinition> 

     <RowDefinition Height="Auto"></RowDefinition> 

     <RowDefinition Height="1*"></RowDefinition> 
    </Grid.RowDefinitions> 

的行是:

  1. WrapPanel
  2. WrapPanel
  3. TextBox

如果這是非常重要的。

回答

7

如果我理解正確,可以使用Auto,然後將MaxHeight屬性綁定到GridHeight。也許是這樣的:

MaxHeightConverter.cs:

public class MaxHeightConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value == null) 
      throw new ArgumentException("MaxHeightConverter expects a height value", "values"); 

     return ((double)value/2); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

MyWindow.xaml:

... 
xmlns:converters="clr-namespace:MyApp.Namespace" 
... 
<Window.Resources> 
    <converters:MaxHeightConverter x:Key="MaxHeightValue" /> 
</Window.Resources> 

<Grid x:Name="root"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"></RowDefinition> 
     <RowDefinition Height="Auto"></RowDefinition> 
     <RowDefinition Height="1*"></RowDefinition> 
    </Grid.RowDefinitions> 

    <WrapPanel > 
     <WrapPanel.MaxHeight> 
      <Binding Converter="{StaticResource MaxHeightValue}" ElementName="root" Path="ActualHeight" /> 
     </WrapPanel.MaxHeight> 
    </WrapPanel> 
</Grid> 
... 

希望這有助於。

+1

感謝。按照我想要的方式工作。我只需要在'MaxHeightConverter'中將演員從'(int)'改成'(double)'。 – Onur

+0

Hoot!謝謝。這工作。 –

5

的另一種方式,你可以只用XAML將綁定到一個隱藏的對象,它是你想要的高度做到這一點:

<Grid> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="1*" /> 
      <RowDefinition Height="1*" /> 
     </Grid.RowDefinitions> 
     <Border Background="White" Visibility="Hidden" x:Name="HalfHeightRow" x:FieldModifier="private" /> 
    </Grid> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="Auto" /> 
      <RowDefinition Height="Auto" /> 
      <RowDefinition Height="*" /> 
     </Grid.RowDefinitions> 

     <Border Height="1000" Background="Red" MaxHeight="{Binding ActualHeight, ElementName=HalfHeightRow}" /> 
     <Border Grid.Row="1" Height="100" Background="Green" /> 
     <Border Grid.Row="2" Background="Blue" /> 
    </Grid> 

+0

有趣的方法。在更復雜的情況下,它可能對我有用。但現在我會堅持Jespers解決方案。 – Onur