繁体   English   中英

标签文本未从ViewModel Xamarin表单更新

[英]Label Text not Updating from ViewModel Xamarin Forms

我正在尝试获取标签文本以在我的应用程序前端更新。 目前,Im正在使用消息中心向视图模型发送通知,并增加一个应在视图标签上更新的数字。 我正在使用Xamarin Forms和PCL。 我可以获得在调试中注销的号码,因此我知道消息中心正在运行。 但是它没有更新视图。

相关的Xaml:

    <Label Text="{Binding counter}"

           Grid.Row="0"/>

后面的代码:

 public partial class DriverDashboardView : ContentPage
{
    private DriverDashboardViewModel driverdashboardviewmodel;

    public DriverDashboardView()
    {

        InitializeComponent();

        this.Title = "Driver's Dashboard";
        BindingContext = driverdashboardviewmodel = new DriverDashboardViewModel();
        dataList.ItemTapped += DataList_ItemTapped;


    }

    private void DataList_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        DisplayAlert("Route Information","Various Data","OK");
    }

    protected async override void OnAppearing()
    {
        base.OnAppearing();
        await driverdashboardviewmodel.GetLabelInfo();
    }

}

视图模型:

 public class DriverDashboardViewModel:BaseViewModel,INotifyPropertyChanged
{

   private int messageCounter { get; set; }
   public string counter { get { return messageCounter.ToString(); }
                        set {
                            if (Equals(value, messageCounter)) return;
                            messageCounter = Convert.ToInt32(value);
                            OnPropertyChanged(nameof(counter));

                             } }


    public DriverDashboardViewModel()
    {

        MessagingCenter.Subscribe<App>((App)Application.Current, "Increase", (variable) => {

            messageCounter++;
        });

    }



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

以及实现消息中心的相关部分:

Foregroundmessages.cs:

MessagingCenter.Send((App)Xamarin.Forms.Application.Current, "Increase");

如前所述,消息传递中心工作正常。 它可以到达视图模型,但不会将计数器变量更新为视图。 我尝试将计数器设置为int和字符串,因此在get和set中进行了转换。 我还尝试了可观察的集合,但这似乎是多余的,因为它是单个变量而不是集合或列表。

有任何想法吗?

您的代码正在更新私有messageCounter属性,而不是要绑定到的公共counter属性。 更新messageCounter不会引发PropertyChanged

MessagingCenter.Subscribe<App>((App)Application.Current, "Increase", (variable) => {
  messageCounter++;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM