C# 绑定网格';s的高度和宽度基于其子控件

C# 绑定网格';s的高度和宽度基于其子控件,c#,wpf,grid,C#,Wpf,Grid,我在网格内有图像,我想将网格的高度和宽度分别设置为图像的源高度+10和宽度+10。我写了下面的代码,但它不工作 如何执行此操作?仅使用边距属性如何: <Grid VerticalAlignment="Top" HorizontalAlignment="Center" Margin="10"> <Grid.ColumnDefinitions> <ColumnDefinition Width="{Binding ElementName=im

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




如何执行此操作?

仅使用
边距属性如何:

<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>

图像控件中使用边距属性