MVVM.Xamarin.它是否不会更改文本(LabelText)的值?为什么



xaml:Codigo-xaml
<ContentPage。BindingContext>local:ClockRegisterViewModel/<ContentPage。BindingContext>

<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{公共类ClockRegisterViewModel{公共ObservableCollection ListStudents{get;set;}

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;
}
}
}
}

在视图模型中,当值发生更改时,它不会通知UI进行更新。您需要使视图模型实现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://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm

最新更新