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

本文关键字:高度 绑定 grid 控件 根据 | 更新日期: 2023-09-27 18:13:35

我在网格中有图像,我想设置网格的高度和宽度分别为图像的源高度+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>

如何做到这一点?

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

如果只使用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>

您可以将代码缩减为:

 <Grid>
     <Image Name="imagePreview" Grid.Row="0" Grid.Column="0"
         VerticalAlignment="Center"
         HorizontalAlignment="Center"
         Stretch="None" Margin="10"/>
 </Grid>
Image控件中使用Margin属性