Search code examples
wpfmultibinding

Converter not working for row definition height


I am using a multi value converter to get height of a row. But I get the following error on height binding (seen via snoop).

System.Windows.Data Error: 5 : Value produced by BindingExpression is not a valid for target property. Value='33.44444' MultibindingBindingExpression:target element is 'RowDefinition'. target property is 'Height' (type 'GridLength')

Even after googling a lot, I could not solve this problem. Can anyone please help me to resolve this.

My Row definitions:

  <Grid.RowDefinitions>
                            <RowDefinition>
                                <RowDefinition.Height>
                                    <MultiBinding 
   Converter="{StaticResource HeightConverter}">
                                        <Binding Path="Height" 
 RelativeSource="{RelativeSource AncestorType=controls:TestControl, 
 Mode=FindAncestor}" UpdateSourceTrigger="PropertyChanged"></Binding>
                                        <Binding Path="MR" 
  RelativeSource="{RelativeSource AncestorType=controls:TestControl,
  Mode=FindAncestor}" UpdateSourceTrigger="PropertyChanged"></Binding>
                                        <Binding Path="BR" 
  RelativeSource="{RelativeSource AncestorType=controls:TestControl, 
  Mode=FindAncestor}" UpdateSourceTrigger="PropertyChanged"></Binding>
                                    </MultiBinding>
                                </RowDefinition.Height>
                            </RowDefinition>
                            <RowDefinition Height="Auto"></RowDefinition>
                            <RowDefinition Height="*"></RowDefinition>
                        </Grid.RowDefinitions>

My Height Converter code:

    public object Convert(object[] values, Type targetType, object 
    parameter, CultureInfo culture)
    {
        var TH = (double)values[0];
        var TR = (double)values[1];
        var BR = (double)values[2];

        var per = TR + BR;
        var per2 = (TR/per)*100;

        return (int)(per2/TH)*100;
    }

Thanks & Regards


Solution

  • You are returning int for your Grid Height from your Converter. it should be GridLength

    See below from MSDN

     public System.Windows.GridLength Height { get; set; }
     Member of System.Windows.Controls.RowDefinition
    

    Summary:

    Gets the calculated height of a System.Windows.Controls.RowDefinition element, or sets the System.Windows.GridLength value of a row that is defined by the System.Windows.Controls.RowDefinition.

    Returns:

    The System.Windows.GridLength that represents the height of the row. The default value is 1.0.


    Return GridLength from your converter like below,

    return new GridLength(0, GridUnitType.Star); // Or
    return new GridLength(per2/TH)*100);