在XAML中将网格星大小保持为常量

时间:2014-02-16 13:07:56

标签: wpf visual-studio-2010 xaml resources

<Grid.RowDefinitions>
    <RowDefinition Height="4*"/>
    <RowDefinition Height="3*"/>
</Grid.RowDefinitions>

我想在XAML中的其他地方定义4/3比率,然后使用它。像这样:

<System:Double x:Key="Top_Part">4</System:Double>
<System:Double x:Key="Bottom_Part">3</System:Double>

<Grid.RowDefinitions>
    <RowDefinition Height="{StaticResource Top_Part}"/>
    <RowDefinition Height="{StaticResource Bottom_Part}"/>
</Grid.RowDefinitions>

当然,此代码不正确,不会产生预期的效果。我怎么能正确地做到这一点?

1 个答案:

答案 0 :(得分:5)

RowDefinition的{​​{3}}类型为Height property,因此您需要在资源中创建GridLength个实例:

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Window.Resources>
    <GridLength  x:Key="Top_Part">4*</GridLength>
    <GridLength  x:Key="Bottom_Part">3*</GridLength >
  </Window.Resources>
  <Grid>  
    <Grid.RowDefinitions>
        <RowDefinition Height="{StaticResource Top_Part}"/>
        <RowDefinition Height="{StaticResource Bottom_Part}"/>
    </Grid.RowDefinitions>
    <Grid Background="Blue" Grid.Row="0"/>
    <Grid Background="Red" Grid.Row="1"/>
  </Grid>
</Window>