[SOLVED] Create in .NET MAUI a 2D array as squares with binding

Issue

This Content is from Stack Overflow. Question asked by TigraSc

I came across a training task at MAUI to implement a two-dimensional array matrix in the form of interactive squares. Inside the square is a vertical or horizontal stripe. When you click on a square, the strip changes in orientation. When user click all strip as vertical or horizontal programm stoping.

I’m thinking of writing 0 or 1 into a two-dimensional array (byte[,]). Where 0 is a horizontal strip, 1 is a vertical one. When you click on a cell, the opposite number should be written to the array. That is, if it was 0, it will become 1.

enter image description here

Any ideas how to organize this through binding?



Solution

In order to do it through model you should define view model, which then could be definedas readonly field in your view class.

Also it would require little bit of extra work to define converter, but below is sample implementation:

First view model code:

public class SimpleVm : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Orientation _orientation;

    public Orientation Orientation
    {
        get => _orientation;
        set
        {
            _orientation = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Orientation)));
        }
    }

    public void ChangeOrientation()
    {
        Orientation = Orientation == Orientation.Horizontal
            ? Orientation.Vertical
            : Orientation.Horizontal;
    }
}

For that i defined simple enumration:

/// <summary>
/// To make the code cleaner, you can search for some
/// BCL defined e for taht.
/// </summary>
public enum Orientation
{
    Vertical,
    Horizontal,
}

Code-behind code for view is pretty simple (note that you could also define event handler as binding from view to viewmodel):

public partial class MainPage : ContentPage, INotifyPropertyChanged
{
    private readonly SimpleVm _vm = new();

    public MainPage()
    {
        InitializeComponent();
        BindingContext = _vm;
    }

    private void OnButtonClicked(object sender, EventArgs e)
    {
        _vm.ChangeOrientation();
    }
}

And here’s XAML defining just square image and button to change its orientation:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MauiApp1"
             x:Class="MauiApp1.MainPage">

    <ContentPage.Resources>
        <local:OrientationConverter x:Key="OrientationConverter" />
    </ContentPage.Resources>
    <ScrollView>
        <VerticalStackLayout 
            Spacing="25" 
            Padding="30,0" 
            VerticalOptions="Center">

            <Image
                Source="square_with_stripe.png"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                Rotation="{Binding Orientation, Converter={StaticResource OrientationConverter}}"
                HeightRequest="200"
                HorizontalOptions="Center" />
            <Button 
                x:Name="ChangeOrientation"
                Text="Click me"
                SemanticProperties.Hint="Changes orientation"
                Clicked="OnButtonClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

Note that I defined OrientationConverter in page resources, which is defined in class:

public class OrientationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (Orientation)value switch
        {
            Orientation.Horizontal => 0,
            Orientation.Vertical => 90,
        };
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (int)value switch
        {
            0 => Orientation.Horizontal,
            90 => Orientation.Vertical,
            _ => Orientation.Horizontal,
        };
    }
}


This Question was asked in StackOverflow by TigraSc and Answered by MichaƂ Turczyn It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?