Using ValueConverter to position a Line relative to its parent ActualHeight and another ViewModel property

252 Views Asked by At

I have a property in my ViewModel called RelativeHeight, which is a double ranging from 0 to 1.

In my View, I have an horizontal line whose width is the same of its container (via Element Binding), but I want it to have its vertical position relative to the size of the container.

For example, if RelativeHeight is 0.3, and the container's ActualHeight is 200, then Line.X1 and Line.X2 would be 60 each.

Following code is what I got, but don't know how to use (or even if I should use in the first place) some IValueConverter because usually I can't get properties from the view whan calling the Convert method...

<Line Stroke="Red" Opacity="0.5" StrokeThickness="5"
      X1="0" X2="{Binding ActualWidth, ElementName=Graphs}"
      Y1="{Binding RelativeHeight, Converter=MaybeSomeConversion}"
      Y2="{Binding RelativeHeight, Converter=MaybeSomeConversion}" />
1

There are 1 best solutions below

0
On

Got it with IMultiValueConverter, like this (variable names in portuguese):

... (resource dictionary)

<views:ConversorNível x:Key="conversorNivel"/>

....

<Line x:Name="line" Stroke="Red" Opacity="0.6" Grid.ColumnSpan="5" StrokeThickness="2"
      X1="0" X2="{Binding ActualWidth, ElementName=Gráficos}"
      Y2="{Binding Y1, ElementName=line}" >
    <Line.Y1>
        <MultiBinding Converter="{StaticResource conversorNivel}">
            <Binding Path="NívelSelecionado" />
            <Binding ElementName="Gráficos" Path="ActualHeight" />
        </MultiBinding>
    </Line.Y1>
</Line>

and in codebehind:

public class ConversorNível : IMultiValueConverter {
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (double)values[0] * (double)values[1];
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}