Skip to content

Instructions 07 MAUI3

Sebastian Szvetecz edited this page Sep 28, 2023 · 2 revisions

Part 7 - .NET MAUI Part 3: Views

Create pages and views, and connect the views to the view-models.

  1. Create the PegSelectionView to select a peg with a Picker
  2. Create the GamePage (the main page of the application) to enter the gamer name, and to start a game
  3. Use constructor injection to bind the view-model to the view
  4. Use a template for the pegs and selection of the color
  5. Build and run the application
  6. Register with the App Center to distribute an application to testers.

Source Code

GamePage - Start a Game

<Grid
    RowDefinitions="Auto, Auto"
    ColumnDefinitions="*, Auto"
    ColumnSpacing="8"
    RowSpacing="8"
    IsVisible="{Binding ViewModel.GameStatus, Mode=OneWay, Converter={StaticResource GameStatusVisibleConverter}, ConverterParameter=Start}">
    <Label
        Grid.Column="0"
        Grid.Row="0"
        VerticalTextAlignment="Center"
        Text="Enter your Gamername:" 
        FontSize="18" />
    <Entry
        Grid.Column="0"
        Grid.Row="1"
        IsEnabled="{Binding ViewModel.IsEnabled, Mode=OneWay}"
        Text="{Binding ViewModel.Name, Mode=TwoWay }"
        Placeholder="Enter your name"/>
    <Button
        Grid.Column="1"
        Grid.Row="1"
        Padding="40,8"
        HorizontalOptions="Fill"
        VerticalOptions="EndAndExpand"
        Text="Start the game"
        IsVisible="{OnIdiom
            Default={Binding ViewModel.GameStatus, Mode=OneWay, Converter={StaticResource GameStatusVisibleConverter}, ConverterParameter=Start},
            Phone=False,
            Watch=False
        }"
        Command="{Binding ViewModel.StartGameCommand, Mode=OneTime}" />
</Grid>

Binding to the View-Model

Use constructor injection to inject the view-model in the view. As part of the implementation to receive a display message, register with the InfoMessage, and display an alert.

public partial class GamePage : ContentPage
{

	public GamePage(GamePageViewModel viewModel)
	{
		ViewModel = viewModel;

		BindingContext = this;
		InitializeComponent();

		WeakReferenceMessenger.Default.Register<InfoMessage>(this, async (r, m) =>
		{
			await DisplayAlert("Info", m.Text, "Close");
		});
	}

	public GamePageViewModel ViewModel { get; }
}

SelectColorTemplate

    <DataTemplate x:Key="SelectColorTemplate">
    <StackLayout>
        <Frame HasShadow="True" BorderColor="DarkGray" CornerRadius="4" HorizontalOptions="Center"
                VerticalOptions="Center" HeightRequest="80" WidthRequest="80">
            <Ellipse 
                Fill="{Binding Mode=OneWay, Converter={StaticResource ColorConverter}}" 
                WidthRequest="60" 
                HeightRequest="60" />
        </Frame>
    </StackLayout>
</DataTemplate>

Clone this wiki locally