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

时间:2017-06-27 15:18:02

标签: c# xamarin xamarin.forms

我正在尝试让我的应用程序结尾前面的标签文本更新。 目前,我使用消息中心向视图模型发送通知,并增加应在视图中的标签上更新的数字。 我使用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中进行转换。 我也试过了可观察的集合,但这似乎是多余的,因为它的单个变量不是集合或列表。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您的代码正在更新私有counter属性,而不是您要绑定的公共messageCounter属性。更新PropertyChanged不会导致MessagingCenter.Subscribe<App>((App)Application.Current, "Increase", (variable) => { messageCounter++; }); 触发。

public int getDateDiff(int OrderID) {
    Connection conn = DBConnection.getConnection();
    Integer diff = null;
    String getdiffSQL = "SELECT DATEDIFF( DAY , StartDate , EndDate ) FROM CarOrder WHERE OrderID = ?;";
    try {
        PreparedStatement pstm = conn.prepareStatement(getdiffSQL); 
        pstm.setInt(1, OrderID);
        ResultSet rs = pstm.executeQuery(getdiffSQL);
            while (rs.next()) {
                diff = rs.getInt(1);
            }
        }
     catch (SQLException ex) {
        System.out.println("Error: " + ex.getMessage());
    }
    return diff;
}