Xamarin形式:如何从viewmodel更改标签文本值?

时间:2018-09-19 05:55:24

标签: xamarin.forms label viewmodel

从新页面按下后退按钮时,我想更改上一页的标签文本值。我从新页面开始使用messagecenter功能,并将代码流重定向到viewmodel中的RefreshCustomerDetails()。

我尝试如下。

string _fullname = "";
public string FullName
{
    protected set
    {
        if (_fullname != value)
        {
            _fullname = value;
            OnPropertyChanged("FullName");
        }
    }
    get { return _fullname; }
}

public void RefreshCustomerDetails()
{
   //FullName = null;
   FullName = Application.Current.Properties["customerFullName"].ToString();
}

   <Label 
      x:Name="title_label"
      Text="{Binding FullName}"
      Font="Bold,18" 
      TextColor="Black"
      Margin="-20,0,0,0"
      HorizontalOptions="CenterAndExpand" 
      VerticalOptions="Center"/>

从Local db获取Fullname值并像上面的代码一样将其绑定,但是在按一下臀部时,名称没有变化。尝试分配空值,该值也不起作用。

我的代码有任何更正吗?

2 个答案:

答案 0 :(得分:0)

您的代码看起来不错,它应该可以工作。您的ViewModel是否继承自INotifyPropertyChangedOnPropertyChanged()这是必需的:

public class MyViewModel : INotifyPropertyChanged
{
    // stuff ...
}

答案 1 :(得分:0)

更新如下代码,删除RefreshCustomerDetails()  并在 MessagingCenter 内添加 Device.BeginInvokeOnMainThread

Text="{Binding FullName,Mode=TwoWay}"


MessagingCenter.Subscribe<AddCustomerBySOPage>(this, "Refresh", (sender) =>
     {
       Device.BeginInvokeOnMainThread(() =>
         {
            FullName = Application.Current.Properties["customerFullName"].ToString();
          });
     });