根据子控件绑定Grid的高度和宽度

时间:2014-07-18 13:31:40

标签: c# wpf grid

我在网格中有图像,我想将网格的高度和宽度分别设置为图像的源高度+ 10和宽度+ 10。我写了下面的代码,但它没有用。

  
    

<Grid VerticalAlignment="Top" HorizontalAlignment="Center"> <Grid.ColumnDefinitions> <ColumnDefinition Width="{Binding ElementName=imagePreview, Path=imagePreview.Source.Width}" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions > <RowDefinition Height="{Binding ElementName=imagePreview, Path=imagePreview.Source.Height}" /> </Grid.RowDefinitions> <Image Name="imagePreview" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center" Stretch="None"/>
</Grid>

  

怎么做?

2 个答案:

答案 0 :(得分:1)

使用Margin属性怎么样?:

<Grid VerticalAlignment="Top" HorizontalAlignment="Center" Margin="10">
    <Grid.ColumnDefinitions>
       <ColumnDefinition  Width="{Binding ElementName=imagePreview, 
           Path=imagePreview.Source.Width}" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions >
       <RowDefinition Height="{Binding ElementName=imagePreview, 
           Path=imagePreview.Source.Height}" />
    </Grid.RowDefinitions>
    <Image Name="imagePreview" Grid.Row="0" Grid.Column="0"
       VerticalAlignment="Center" HorizontalAlignment="Center" Stretch="None"/>     
</Grid>

答案 1 :(得分:1)

您可以将代码缩减为:

 <Grid>
     <Image Name="imagePreview" Grid.Row="0" Grid.Column="0"
         VerticalAlignment="Center"
         HorizontalAlignment="Center"
         Stretch="None" Margin="10"/>
 </Grid>

图片控件中使用保证金属性。