【问题标题】:Progress Bar Not Updating Xamarin Forms MVVM进度条未更新 Xamarin 表单 MVVM
【发布时间】:2020-04-12 12:15:16
【问题描述】:

我知道以前有人问过这个问题,但我已经花了很长时间没有任何帮助。

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

配方.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>

食谱.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,执行逻辑,并随之更新进度条,但是出于调试目的,我只想在按钮命令执行时将进度更改为100%

如有任何帮助,将不胜感激,谢谢

【问题讨论】:

  • 您预计会发生什么?您不会增量更改ProgressValue - 您只需将其设置为 1,然后调用您的服务。如果您只想指示用户正在发生某事,请使用 ActivityIndi​​cator。
  • 啊,那我可能错过了什么。对 Xamarin 来说非常新,我看到的大多数教程都只是将 Progress 绑定设置为 1。我也尝试过 Activity Indicator,但是类似的问题,在通过绑定 IsBool 将可见性 ect 设置为 true 时通过手机进行调试时从未显示过
  • ProgressBar 的值介于 0 和 1 之间,表示任务的完成百分比。它旨在显示渐进式进展。
  • 啊,谢谢,我会回去尝试让 ActivityInidcator 工作。您是否知道为什么我无法按照我之前的评论中描述的那样让它工作?可以提供代码哈哈。感谢帮助
  • @GeorgeStrike 请看我下面的回复。

标签: c# xamarin xamarin.forms xamarin.android


【解决方案1】:

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

关于绑定ActivityIndi​​cator isvisible,我做一个例子大家可以看看:

请看以下代码,先显示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));
        }
    }
}

截图:

【讨论】:

    猜你喜欢
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多