Привязки данных не обновляются с помощью OnPropertyChanged - PullRequest
0 голосов
/ 11 июля 2019

Создание моего первого приложения с помощью Xamarian.Forms.У меня есть базовое меню и домашняя страница с несколькими ярлыками и кнопкой, чтобы я мог связать некоторые данные и метод и убедиться, что логический код для моей игры работает.Я установил привязки данных к меткам, они появляются на экране.Однако я не был уверен, что мои привязки не обновлялись или моя команда не была обязательной.Поэтому я закомментировал ICommand, удалил привязку и поместил метод, чтобы продвигать поворот в код за моим xaml.Даже после этого данные не обновляются при нажатии кнопки, что заставляет меня поверить, что это проблема с моим OnPropertyChanged и привязками данных.Я искал в Интернете и связанных с ним вопросах, я реализовал несколько различных способов написания получения и набора для привязок, написал мою функцию OnPropertyChanged несколькими различными способами, и все же ничего не происходит, когда нажимается кнопка панели инструментов на домашней странице.

Вот мой HomePageViewModel.cs, содержащий INotifyPropertyChanged

*** Отредактировано с учетом изменений, внесенных после получения значения дня для обновления:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Input;
using Engine;
using Xamarin.Forms;

namespace TestApp
{
    public class HomePageViewModel : INotifyPropertyChanged
    {
        public static Player _player = World.Player1;

        public string Day = World.TrueDay.ToString();

        public string MoneyValue = Convert.ToInt32(Math.Floor(World.Player1.PlayerMoney)).ToString();

        public string CurrentLocation = _player.CurrentLocation.Name;


        public HomePageViewModel()
        {
            OnTurn = new Command(execute: On1Turn);
        }

        public ICommand OnTurn { get; private set; }

        public string CurrentDay
        {

            get { return Day; }

            set { Day = value; OnPropertyChanged(); }

        }

        public string Money
        {

            get { return MoneyValue; }

            set { MoneyValue = value; OnPropertyChanged(); }
        }

        public string PlayerLocation
        {

            get { return CurrentLocation; }

            set { CurrentLocation = value; OnPropertyChanged(); }
        }

        void On1Turn()
        {

            World.TrueDay = World.TrueDay + 1;

            CurrentDay = World.TrueDay.ToString();

            World.Player1.PlayerMoney = World.Player1.PlayerMoney + 1000;

            MoneyValue = Convert.ToInt32(Math.Floor(World.Player1.PlayerMoney)).ToString();

            OnPropertyChanged(Money);

        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }    
    }
}

Вот моя домашняя страница.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local1="clr-namespace:TestApp"
             mc:Ignorable="d"
             x:Class="TestApp.HomePage">

    <ContentPage.BindingContext>
        <local1:HomePageViewModel/>
    </ContentPage.BindingContext>

    <ContentPage.ToolbarItems>
        <ToolbarItem Text="+24hrs" Clicked="ToolbarItem_Clicked"  />
    </ContentPage.ToolbarItems>


    <StackLayout Padding="20">

        <StackLayout Orientation="Horizontal">
            <Label Text="Money:" HorizontalOptions="Start"/>
            <Label x:Name="lblPlayerMoney"  Text="{Binding Money, Mode=OneWay}" HorizontalOptions="FillAndExpand"/>
        </StackLayout>

        <StackLayout Orientation="Horizontal" VerticalOptions="EndAndExpand" Margin="0,-40,0,0">
            <Label Text="Current Location:" HorizontalOptions="CenterAndExpand"/>
            <Label x:Name="lblPlayerLocation" Text="{Binding PlayerLocation, Mode=OneWay}"  HorizontalOptions="CenterAndExpand"/>
        </StackLayout>

        <StackLayout Orientation="Horizontal" VerticalOptions="StartAndExpand">
            <Label Text="Current Day:" HorizontalOptions="CenterAndExpand" Margin="30,0,0,0"/>
            <Label x:Name="lblCurrentDay" Text="{Binding CurrentDay, Mode=OneWay}" HorizontalOptions="CenterAndExpand"/>
        </StackLayout>

    </StackLayout>




</ContentPage>

И HomePage.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Engine;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TestApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {
        public HomePage()
        {
            InitializeComponent();

            //BindingContext = new HomePageViewModel();
        }

        private void ToolbarItem_Clicked(object sender, EventArgs e)
        {
            World.TrueDay = World.TrueDay + 1;

            World.Player1.PlayerMoney = World.Player1.PlayerMoney + 1000;
        }
    }
}

Любое понимание проблемы будет высоко оценено, поскольку я новичок в Xamarian.Forms и OnPropertyChanged.особенность в общем.Спасибо за время!

РЕДАКТИРОВАТЬ ******

Вот World.cs, где я установил свойства, если это поможет

using System;
using System.Collections.Generic;
using System.Text;

namespace Engine
{
    public class World
    {
        public static decimal TrueDay = 1;
        //public string LocationText = Player1.CurrentLocation.Name.ToString();

        public static Player Player1;

        public static readonly List<Location> Locations = new List<Location>();

        public const int LOCATION_ID_OSHAWA = 1;
        public const int LOCATION_ID_TORONTO = 2;

        public static void GenerateWorld()
        {
            PopulateLocations();
            Player1 = new Player("Jordan", LocationByID(LOCATION_ID_OSHAWA), 5000);
        }
        private static void PopulateLocations()
        {
            Location oshawa = new Location(LOCATION_ID_OSHAWA, "Oshawa");
            Location toronto = new Location(LOCATION_ID_TORONTO, "Toronto");

            Locations.Add(oshawa);
            Locations.Add(toronto);
        }
        public static Location LocationByID(int id)
        {
            foreach (Location location in Locations)
            {
                if (location.ID == id)
                {
                    return location;
                }
            }

            return null;
        }
    }
}

1 Ответ

0 голосов
/ 11 июля 2019

Не слишком понимая логику проекта, но если вы хотите изменить данные модели, можете сделать следующее:

HomePage.xaml.cs

namespace TestApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {
        HomePageViewModel homePageViewModel = new HomePageViewModel();
        public HomePage()
        {
            InitializeComponent();

            BindingContext = homePageViewModel ;
        }

        private void ToolbarItem_Clicked(object sender, EventArgs e)
        {
            homePageViewModel.CurrentDay = xxx ;

            homePageViewModel.xxxxx = xxxx;
            //Something like this can change model data
        }
    }
}

Вот пример привязки данных, к которому можно обратиться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...