Search code examples
c#mvvmmaui

MAUI - how to bind VisualElement property to a variable in a View


I want to bind my RowDefinition Height to a variable in the code behind of my View class.

The problem is that I have defined the BindingContext of my MainPage to a MainPageViewModel and now I need to bind it to MainPage again. I was trying to use self-bind but it is not created for such problems or I don't know how to use it correctly.

The code that I have tried:

<Grid.RowDefinitions BindingContext="{Binding Source={RelativeSource Self}, Path=MainPage}"> <!--attempt to set BindingContext to MainPage.xaml.cs-->
    <RowDefinition Height="*"/>
    <RowDefinition Height="75"/>
    <RowDefinition Height="10"/>
    <RowDefinition Height="{Binding TestHeight}"/> <!--This XAML is in MainPage.xaml, this "TestHeight" variable is in MainPage.xaml.cs-->
    <RowDefinition Height="10"/>
</Grid.RowDefinitions>

Solution

  • You set BindingContext="{Binding Source={RelativeSource Self}, that means you set the BindingContext to the Grid itself and the Grid doesn't have mainpage Property. That's the reason why it doesn't work.

    As a solution, you may either use Relative binding or x:reference

    If you want to use Relative Binding, try the following way to set the BindingContext of the Grid (not RowDefinition) to MainPage,

    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
            ...
             xmlns:local="clr-namespace:MauiTest">
    
    
    <Grid BindingContext="{Binding Source={RelativeSource AncestorType={x:Type local:MainPage}}}">
        <Grid.RowDefinitions>
            <!--attempt to set BindingContext to MainPage.xaml.cs-->
            ...
            <RowDefinition Height="{Binding TestHeight}"/>
    

    If you want to use x:Reference, remember to set the x:Name for the MainPage, and use x:Reference Binding expression.

    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             ...
             x:Name="mainpage"
             >
    
    <Grid>
       <Grid.RowDefinitions>
           <!--attempt to set BindingContext to MainPage.xaml.cs-->
           <RowDefinition Height="*"/>
           ...
           <RowDefinition Height="{Binding TestHeight,Source={x:Reference mainpage}}"/>
    

    Both of the above ways work. Please let me know if you have any question.