MVVM。 Xamarin。它不会改变文本(LabelText)的值吗?为什么?

MVVM. Xamarin. Does it not change the value of the text (LabelText)? Why?

xaml: 科迪戈 xaml
local:ClockRegisterViewModel/

            <Label Text="Enter your ID: " FontSize="21" TextColor="Red" />
            <Entry x:Name="imputEntry"
                   Text="{Binding GetInputValue}"
                   FontSize="Large" Placeholder="Enter your ID" 
                   ReturnCommand="{Binding AddTodoCommand}"
            />
            <Label Text="{Binding LabelText}" FontSize="21" TextColor="Blue"/>
        </StackLayout>
    </ContentPage>

MVVM Codigo: 命名空间 StudentLoginApp { public class ClockRegisterViewModel { public ObservableCollection ListStudents { get;放; }

    public ClockRegisterViewModel()
    {
        ListStudents = new ObservableCollection<ListStudent>();
        ListStudents.Add(new ListStudent("01", "Dante"));
        ListStudents.Add(new ListStudent("02", "Efrain"));
        ListStudents.Add(new ListStudent("03", "Bryan"));
        ListStudents.Add(new ListStudent("04", "Adams"));
        ListStudents.Add(new ListStudent("05", "Nick"));
    }
    public ICommand AddTodoCommand => new Command(CheckId);
    public string GetInputValue { get; set; }
    public string LabelText { get; set; }

    public void CheckId()
    {
        this.LabelText = "test";

        var sd = ListStudents.Where(x => x.IdStudent == GetInputValue);
        if (!sd.Any())
        {
            UserDialogs.Instance.Alert(new AlertConfig
            {
                Message = "ID incorrect",
                OkText = "OK",
                Title = "Validation Check In"
            });
            return;
        }
    }

}
}

在你的viewmodel中,当值改变时,它不会通知UI到update.You需要让你的viewmodel实现INotifyPropertyChanged接口。

如:

public class ClockRegisterViewModel : INotifyPropertyChanged

然后您需要一个事件来通知 UI 当您的视图模型中的值发生更改时。

public event PropertyChangedEventHandler PropertyChanged;

另外,设置值时,需要调用事件PropertyChanged。如

string labelText;
public string LabelText
    {
        set
        {
            if (labelText != value)
            {
                labelText = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("LabelText"));
                }
            }
        }
        get
        {
            return labelText;
        }
    }

最后,绑定xaml中的labelText。

<Label Text="{Binding labelText}" FontSize="21" TextColor="Blue"/>

如果需要更多信息,可以查看官方文档:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm