M. Chris
M. Chris

Reputation: 171

Xamarin Binding Grid to ViewModel

Is there any way to bind the properties of a grid (rowdefinitions, columndefintions, rowspacing, columnspacing, etc.) to a ViewModel?

Upvotes: 0

Views: 615

Answers (1)

jgoldberger - MSFT
jgoldberger - MSFT

Reputation: 6098

It always help to look at the source code: https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/Grid.cs#L20

So it does look like rowdefinitions, columndefintions, rowspacing, columnspacing, are bindable properties as evidenced by the code:

    public static readonly BindableProperty RowSpacingProperty = BindableProperty.Create("RowSpacing", ...);

    public static readonly BindableProperty ColumnSpacingProperty = BindableProperty.Create("ColumnSpacing", ...);

    public static readonly BindableProperty ColumnDefinitionsProperty = BindableProperty.Create("ColumnDefinitions", ...);

    public static readonly BindableProperty RowDefinitionsProperty = BindableProperty.Create("RowDefinitions", ...);

UPDATE: So here is what needs to be done to make this binding work:

If using a Bindings Value Converter, make sure it never returns null.

Then, protect against any binding resolution by assigning the Grid's TargetNullValue and FallbackValue to an empty Row/ColumnDefinitionCollection (using, e.g., a StaticResource).

To do this, first make a static resource that is just a Row/ColumnDefinitionCollection in App.xaml:

<Application.Resources>
    <ResourceDictionary>
        <RowDefinitionCollection x:Key="NullRowDefs" />
        <ColumnDefinitionCollection x:Key="NullColDefs" />
    </ResourceDictionary>
</Application.Resources>

Then set the TargetNullValue and the FallbackValue properties of the Grid to the above static resources:

 <Grid RowDefinitions="{Binding RowSize, TargetNullValue={StaticResource NullRowDefs}, FallbackValue={StaticResource NullRowDefs}}"
       ColumnDefinitions="{Binding ColumnSize, TargetNullValue={StaticResource NullColDefs}, FallbackValue={StaticResource NullColDefs}}"
       x:Name="grid">

Doing the above should resolve the ArgumentException.

UPDATE: This binding should work without supplying the TargetNullValue and FallbackValue. A bug was discovered and a PR has been created, so this should be fixed in an upcoming release, but in the meantime, use the workaround.

Upvotes: 1

Related Questions