进度条未更新Xamarin形式MVVM

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

我知道这已经被问过了,但是我已经花了很长时间,没有任何帮助。

我正在尝试从ViewModel更新进度条,但不会更新。

Recipe.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"
             mc:Ignorable="d"
             x:Class="FitnessScript.Views.Recipes">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Please Enter Ingredients and Requirements!" 
                HorizontalOptions="Center"
                VerticalOptions="Start" HorizontalTextAlignment="Center" TextType="Text" 
                Margin="0,20,0,0"
                FontSize="25"/>
            <Label Text="Enter Ingredients" Margin="5"/>
            <Entry x:Name="Ingredients"
                   Text="{Binding Ingredients}"
                   Placeholder="Ingredients"
                   PlaceholderColor="LightGray" />

            <Label Text="Enter Calories" Margin="5"/>
            <Entry x:Name="Calories"
                   Text="{Binding Calories}"
                   Placeholder="Calories"
                   PlaceholderColor="LightGray" />

            <Button x:Name="RecipeSearchBtn"
                    Text="Find Recipes"
                    Command="{Binding RequestRecipeCommand}" />
            <ProgressBar x:Name="ProgressB"
                         Progress="{Binding ProgressValue}"
                         ProgressColor="Purple"
                         IsVisible="True"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Recipes.xmal.cs

namespace FitnessScript.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Recipes : ContentPage
    {
        RecipeSearchViewModel recipeSearchViewModel;
        public Recipes()
        {
            recipeSearchViewModel = new RecipeSearchViewModel();
            InitializeComponent();
            BindingContext = recipeSearchViewModel;
        }
    }
}

RecipeSearchViewModel

namespace FitnessScript.ViewModels
{
    public class RecipeSearchViewModel : BaseViewModel
    {
        private static readonly IRecipeService _recipeService = new RecipeService();
        private readonly BackgroundWorker worker;

        #region Getters/Setters 
        string _ingredients;
        public string Ingredients
        {
            get { return _ingredients; }
            set
            {
                _ingredients = value;
                OnPropertyChanged("Ingredients");
            }
        }

        int _calories;
        public int Calories
        {
            get { return _calories; }
            set
            {
                _calories = value;
                OnPropertyChanged("Calories");
            }
        }
        float _progressValue;
        public float ProgressValue
        {
            get { return _progressValue; }
            set
            {
                _progressValue = value;
                OnPropertyChanged("ProgressValue");
            }
        }

        #endregion

        public RecipeSearchViewModel()
        {
            this.worker = new BackgroundWorker();
        }

        public Command RequestRecipeCommand
        {
            get
            {
                return new Command(async () => await RequestRecipe());
            }
        }

        private async Task RequestRecipe()
        {
            await Task.Run(() =>
            {
                Device.BeginInvokeOnMainThread(() =>
                { ProgressValue = 1; }
                );
            });
            List<string> ingredientsList = await _recipeService.GetRecipe(Ingredients, Calories);
            App.Current.MainPage.DisplayAlert("Success", $"{Ingredients}, {Calories}", "Close");
        }
    }
}

我已经厌倦了许多不同的选择,例如将ProgressValue设置为Double和Decimal,强制UI线程,无论是否在OnPropertyChange()中添加参数。我也尝试过背景工程,但可悲的是。我正在通过USB使用S10 +进行调试,因为我更喜欢仿真。

总体目标是按下RecipeSearchBtn,执行逻辑并更新进度条,但是出于调试目的,我只想在执行button命令时将进度更改为100%

任何帮助,都会感激,谢谢

c# xamarin xamarin.forms xamarin.android
1个回答
0
投票

还我尝试了活动指示器,但是类似的问题,在通过绑定IsBool将可见性设置为true时通过电话调试时也从未显示过

关于绑定ActivityIndi​​cator是可见的,我做了一个示例,您可以看一下:

[请看下面的代码,首先显示ActivityIndi​​cator,单击按钮以加载数据,将ActivityIndi​​cator设置为isVisible并将IsRunning设置为false。

  <StackLayout>
        <Button
            x:Name="btn1"
            Command="{Binding command1}"
            Text="load data" />

        <ActivityIndicator
            HeightRequest="50"
            IsRunning="{Binding isvisible}"
            IsVisible="{Binding isvisible}"
            WidthRequest="50"
            Color="Red" />
        <ListView ItemsSource="{Binding students}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding name}" />
                            <Label Text="{Binding age}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>


    </StackLayout>

 public partial class Page2 : ContentPage
{
    public Page2()
    {
        InitializeComponent();
        this.BindingContext = new studentviewmodel();
    }
}

public class studentviewmodel:ViewModelBase
{
    public ObservableCollection<studentmodel> students { get; set; }
    public Command command1 { get; set; }
    private bool _isvisible;
    public bool isvisible
    {
        get { return _isvisible; }
        set
        {
            _isvisible = value;
            RaisePropertyChanged("isvisible");
        }
    }
    public studentviewmodel()
    {

        command1 = new Command(loaddata);
        isvisible = true;
        students = new ObservableCollection<studentmodel>();

    }

    private async void loaddata()
    {
        //call service to do other something.
        await Task.Delay(5000);

        students.Add(new studentmodel() { name = "cherry", age = 29 });
        students.Add(new studentmodel() { name = "barry", age = 30 });
        students.Add(new studentmodel() { name = "annine", age = 15 });  

        isvisible = false;

    }
}
public class studentmodel
{
    public string name { get; set; }
    public int age { get; set; }
}

ViewModelBase是实现INotifyPropertyChanged的类,以通知数据已更改。

public class ViewModelBase : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

截图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.