Search code examples
xamluwppercentageivalueconverter

Set xaml object height as % of other xaml object


In a DataTemplate in my UWP app, I want to set the hight of a rectangle as a % of the hight of a image.

My code looks like this.

 <DataTemplate
        x:Key="FlipViewTemplate">
        <Grid>

                <Image
                    x:Name="image"
                    Margin="20"
                    Source="{Binding fullImgUrl}"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center" />
                <Rectangle
                    Height="{Binding 
                   Converter={StaticResource PercentageConverter}, 
                   ElementName=image, 
                   Path=ActualHeight, 
                   ConverterParameter=0.2}"
                    Fill="#FFEA1E1E"
                    VerticalAlignment="Bottom" />

        </Grid>
    </DataTemplate>

And my converter like this

 public class PercentageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return System.Convert.ToDouble(value) *
              System.Convert.ToDouble(parameter);
    }


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


}

My problem is that the value in the converter that should be the actualhight of the image is always 0.


Solution

  • You are already using a Grid, so you could simply define two rows. In the example below the Image control span both rows, i.e. the whole Grid, while the Rectangle resides in the second row only, which has 20% of the whole height.

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="4*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Image Grid.RowSpan="2" .../>
        <Rectangle Grid.Row="1" .../>
    </Grid>