既然我已经完成了一些数据绑定到 mainpage.xaml

问题描述 投票:0回答:1

我对 .net maui 和 c# 总体来说是个新手,我正在尝试编写一个文字游戏,我遇到的问题是在我的主页上使用数据绑定时出现了一些问题:

主页是程序运行时您可以访问的唯一页面,就像应用程序实际上被锁定在其上一样 我必须离开页面的按钮不再起作用,它就在那里 我必须从 github 的长列表中获取随机单词的功能不再触发。我正在使用社区工具包,我应该拥有所有正确的东西才能正常工作

如有任何帮助,我们将不胜感激。

<?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"
             x:Class="Wordle.MainPage"
             xmlns:viewmodel="clr-namespace:Wordle.ViewModel"
             xmlns:models="clr-namespace:Wordle.Models"
             x:DataType="viewmodel:WordleViewModel"
             Title="Welcome to Wordle">

    <ScrollView>
        <VerticalStackLayout
            Spacing="30"
            Padding="20"
            VerticalOptions="Center">
            
            <!--Content of our main page-->
            <Image Source="gametitle.png"
                   HeightRequest="150"/>
            
            <Grid RowDefinitions="*, Auto">
                <VerticalStackLayout BindableLayout.ItemsSource="{Binding CurrentRow}">
                    <BindableLayout.ItemTemplate>
                        <DataTemplate x:DataType="models:GameRows">
                            <HorizontalStackLayout BindableLayout.ItemsSource="{Binding CorrectLetters}"
                                                   HorizontalOptions="Center">
                                <BindableLayout.ItemTemplate>
                                    <DataTemplate x:DataType="models:Letters">
                                        <Button Style="{DynamicResource LettersColor}"
                                                Text="Test"
                                                BackgroundColor="{Binding bgCol}"/>
                                    </DataTemplate>
                                </BindableLayout.ItemTemplate>
                            </HorizontalStackLayout>
                        </DataTemplate>
                    </BindableLayout.ItemTemplate>
                </VerticalStackLayout>
            </Grid>
            <Button x:Name="signInbtn" Text="?" Clicked="signIn"
                    WidthRequest="100" BackgroundColor="Gray" TextColor="White"/>
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>
using System;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.Maui.Storage;
using Wordle.ViewModel;

namespace Wordle
{
    public partial class MainPage : ContentPage
    {
        //Declaring Variables
        private Random rand;
        private List<string> gameWords;
        private HttpClient http;
        private string userGuess;
        private string correctWord;
        private int gamesPlayed;
        private int numWords;
        public string userName;
        private string password;
        public string targetFile;
        public bool isBusy;
        public MainPage(WordleViewModel newView)
        {
            InitializeComponent();
            BindingContext = newView;
            gameWords = new List<string>();
            rand = new Random();
            numWords = gameWords.Count;
            Task task = getGameWords();
            DisplayAlert("Test", correctWord, "Okay");
        }

        public MainPage()
        {
            InitializeComponent();
            BindingContext = new WordleViewModel();
            gameWords = new List<string>();
            rand = new Random();
            numWords = gameWords.Count;
            Task task = getGameWords();
            DisplayAlert("Test", correctWord, "Okay");
        }

        public async Task getGameWords()
        {
            targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "words.txt");
            if (!File.Exists(targetFile))
            {
                http = new HttpClient();
                var response = await http.GetAsync("https://raw.githubusercontent.com/DonH-ITS/jsonfiles/main/words.txt");

                if (response.IsSuccessStatusCode)
                {
                    string contents = await response.Content.ReadAsStringAsync();
                    using (StreamWriter writer = new StreamWriter(targetFile))
                    {
                        writer.Write(contents);
                    }

                    using (StreamReader s = new StreamReader(targetFile))
                    {
                        string line = "";
                        while ((line = s.ReadLine()) != null)
                        {
                            gameWords.Add(line);
                            Console.WriteLine(line);
                            numWords++;
                        }
                    }
                    getRandWord();
                }
            }
            else
            {
                using (StreamReader s = new StreamReader(targetFile))
                {
                    string line = "";
                    while ((line = s.ReadLine()) != null)
                    {
                        gameWords.Add(line);
                        Console.WriteLine(line);
                        numWords++;
                    }
                }
                getRandWord();
            }
        }

        public void getRandWord()
        {
            rand = new Random();
            correctWord = gameWords[rand.Next(gameWords.Count)];

        }
        private void signIn(object sender, EventArgs e)
        {
            Navigation.PushAsync(new SignIn());
        }

        
    }

}
//This is the viewModel im using
using CommunityToolkit.Mvvm.ComponentModel;
using Wordle.Models;
using CommunityToolkit.Mvvm.Input;

namespace Wordle.ViewModel
{
    public partial class WordleViewModel: ObservableObject
    {
        //Declaring Variables
        [ObservableProperty]
        public GameRows[] currentRow;
        private int currentRowIndex;
        private int currentColumnIndex;
        char[] answer;
        char[] userGuess;

        //Constructor to initialize some of the aspects of the ViewModel
        public WordleViewModel()
        {
            currentRow = new GameRows[6]
            {
                new GameRows(),
                new GameRows(),
                new GameRows(),
                new GameRows(),
                new GameRows(),
                new GameRows()
            };
            //Testing storing the correct answer
            answer = "tests".ToCharArray();
        }

        //Getting the user to the next time every time they hit enter
        //[ICommand]
        public void nextLine()
        {
            //Controlling when to move the user to the next row
            var isValid = true;
            if(isValid)
            {
                if(currentColumnIndex != 5)
                {
                    return;
                }

                if(currentRowIndex == 5)
                {

                }
                else
                {
                    currentRowIndex++;
                    currentColumnIndex = 0;
                }
            }
        }
        //[ICommand]
        public void userEntry()
        {
            if(currentColumnIndex == 5)
            {
                return;
            }
        }
    }
}
//This is the model im using
using CommunityToolkit.Mvvm.ComponentModel;

namespace Wordle.Models
{
    public class GameRows
    {
        //Declaring Variables
        int currentRow;
        int currentCol;
        char[] answer;
        char[] userGuess;

        //Constructor to initialize some of the variables of the Model class
        public GameRows()
        {
            CorrectLetters = new Letters[5]
            {
                new Letters(),
                new Letters(),
                new Letters(),
                new Letters(),
                new Letters(),
            };
        }

        //Correct Letters
        public Letters[] CorrectLetters { get; set; }
        public void ValidateAnswer(char[] correctWord)
        {

        }
        
    }
    public partial class Letters : ObservableObject
    {
        [ObservableProperty]
        private char userInput;
        [ObservableProperty]
        private Color colorChange;
        public char CorrectLetter { get; set; }
        public Color bgCol { get; set; }
    }
}
c# .net data-binding maui wordle-game
1个回答
0
投票

我发现你的

App.xaml.cs
文件中的代码与我的不同。将
WelcomePage
设置为
MainPage
将导致项目仅显示
WelcomePage
页面。

由于您在项目中使用了 Shell 架构,因此您可以尝试在 App.xaml.cs 文件中将

AppShell
设置为
Mainpage
,如以下代码。

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        MainPage = new AppShell();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.