Search code examples
wpfmultibindingprogrammatically-createdrowdefinition

How to programmatically create WPF Grid.RowDefintion.Height binding


This should be simple, but I'm stuck! How to create the following multibinding in code and apply it to the given row definition:

<Grid.RowDefinitions>
    <RowDefinition Height="*"/>
        <RowDefinition>
            <RowDefinition.Height>
                <MultiBinding Converter="{StaticResource MyMultiConverter}">
                    <Binding ElementName="obj1" Path="x"/>
                    <Binding ElementName="obj2" Path="y"/> 
                </MultiBinding>
            </RowDefinition.Height>   
        </RowDefinition>
 </Grid.RowDefinitions>

Thanks!


Solution

  • There you go:

    //Create binding
    var binding = new MultiBinding
    {
        Converter = new MyMultiConverter()
    };
    binding.Bindings.Add(new Binding("x") { ElementName = "obj1" });
    binding.Bindings.Add(new Binding("y") { ElementName = "obj2" });
    
    //create RowDefinition
    var definition = new RowDefinition();
    //set binding on HeightProperty
    definition.SetBinding(RowDefinition.HeightProperty, binding);
    
    //'myGrid' is the name of the grid instance
    //add RowDefinition to grid
    myGrid.RowDefinitions.Add(definition);
    

    To be able to handle the grid in codebehind you add a name to the grid:

    <Grid Name="myGrid">
        ...
    </Grid>